/**
 * This js file is used by main.jsp only
 */
// 计算两个日期的间隔天数
function DateDiff(sDate1, sDate2){ //sDate1和sDate2是2002-12-18格式
    var aDate, oDate1, oDate2, iDays
    aDate = sDate1.split("-")
    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2002格式
    aDate = sDate2.split("-")
    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) //把相差的毫秒数转换为天数
    return iDays
}
var mainLayout=null;
var leftLayout=null;
var wins=null;
var popwin;
var cellMCU,cellConference,cellManageAndView,cellConsole,cellAddressBook,cellContent;
var selectedConfNumber=null;
var cdrViewObj,networkRouteViewObj,mcuObj,adminViewObj,sipViewObj,
	registerEndpointViewObj,ptcGroupViewObj,ptcObj,
	confProfileViewObj,onlineConfObj,confCtrlViewObj,menuLinksObj,
	confReserveViewObj,historyViewObj;
var LEVEL_CONF="Conference",LEVEL_SYS="System";
var accesslevel="<c:out value='${sessionScope.loginInfo.accesslevel}' default='Conference' />";

//main.js entrance
$(function(){
	wins=new dhtmlXWindows();
	//wins.setImagePath("<c:url value='/styles/default/images/' />");
	
	dhtmlXLayoutObject.prototype.i18n.collapse = "<fmt:message key='common.collapse'/>";
	dhtmlXLayoutObject.prototype.i18n.expand = "<fmt:message key='common.expand'/>";
	
	if(accesslevel==LEVEL_CONF){
		initLayoutForConfLevel();
		initMenuForConfLevel();
	}else if(accesslevel==LEVEL_SYS){
		initLayoutForSysLevel();
		initMenuForSysLevel();
	}
	
	var mcuDatetime=new MCUDatetime();
	mcuDatetime.init();
	mcuDatetime.start();
});
/**
 * Parse element title property for i18n
 * @param e DOM element
 */
function parseElementTitle(e){
	if(e){
		var _title=e.title||"";
		if(_title.indexOf("$")!=-1){
			e.title=messages.getMsg(_title.replace("$",""))||"";
		}
	}
}

/**
 * Conference level  administrator layout
 */
function initLayoutForConfLevel(){
	mainLayout = new dhtmlXLayoutObject(document.body,"3W");	
	mainLayout.attachHeader("id_header");
    //3W
    //----------
    //|  |  |  |
    //|  |  |  |
    //|  |  |  |
    //|  |  |  |
    //----------
	
	cellConference = mainLayout.cells("a");
	cellContent=mainLayout.cells("b");
	cellAddressBook=mainLayout.cells("c");
	
	cellConference.setWidth(350);
	cellAddressBook.setWidth(350);
	//cellConference.fixSize(true,false);
	
	cellConference.childNodes[0].childNodes[0].childNodes[4].style.display = "none";
	cellContent.childNodes[0].childNodes[0].childNodes[4].style.display = "none";
	cellContent.hideHeader();
	
	cellConference.setText("<fmt:message key='panel.title.conference'/>");
	cellAddressBook.setText("<fmt:message key='panel.title.addressBook'/>");
	mainLayout.setCollapsedText("c","<img src=\"<c:url value='/styles/default/images/addressBook.gif'/>\" width='18px' height='100px' border='0'>");
	
	onlineConfObj=new OnlineConf();
	onlineConfObj.init();
	
	confCtrlViewObj=new ConfCtrlView();
	//confCtrlViewObj.init();
	
	confReserveViewObj=new ConfReserveView();
	//confReserveViewObj.init();
	
	mainLayout.attachEvent("onExpand",function(itemId){
		if(itemId=="c"||itemId=="a"){
			confReserveViewObj.resizeScheduler();
			if(!ptcObj&&itemId=="c"){//lazy load
				//attach participant to addressbook cell
				ptcObj=new PTC();
				ptcObj.init();
			}
		}
		// Disable tooltip for collapsed Layout cell
		this.cells(itemId).removeAttribute("title");
	});
	mainLayout.attachEvent("onCollapse",function(itemId){
		if(itemId=="c"||itemId=="a"){
			confReserveViewObj.resizeScheduler();
		}
		// Disable tooltip for collapsed Layout cell
		this.cells(itemId).removeAttribute("title");
	});
	
	cellAddressBook.collapse();
	ptcObj=new PTC();
	ptcObj.init();
}

/**
 * System level administrator layout
 */
function initLayoutForSysLevel(){
	mainLayout = new dhtmlXLayoutObject(document.body,"4U");
	leftLayout = new dhtmlXLayoutObject(mainLayout.cells("a"),"3E");
	
	//----------------get cells-----------
	cellMCU=leftLayout.cells("c");
	//cellMCU.setSkin("${skin}");
	cellConference=leftLayout.cells("a");
	//cellConference.setSkin("${skin}");
	cellManageAndView=leftLayout.cells("b");
	cellConsole=mainLayout.cells("d");
	cellAddressBook=mainLayout.cells("c");
	cellContent=mainLayout.cells("b");
	
	//------------------init cell size----------------
	mainLayout.cells("a").setWidth(380);
	//cellConference.setHeight(300);
	cellConsole.setHeight(180);
	cellAddressBook.setWidth(300);
	
	//fix size
	//mainLayout.cells("a").fixSize(true,false);
	
	//--------------hide header----------------
	cellContent.childNodes[0].childNodes[0].childNodes[4].style.display = "none";
	cellContent.hideHeader();
	//---------- create view for cellContent---------
	adminViewObj=new AdminView();
	//adminViewObj.init();

    sipViewObj = new SipView();
	
	ptcGroupViewObj=new PTCGroupView();
	//ptcGroupViewObj.init();
	
	confProfileViewObj = new ConfProfileView();
	//confProfileViewObj.init();
	
	confCtrlViewObj=new ConfCtrlView();
	//confCtrlViewObj.init();
	
	registerEndpointViewObj=new RegisterEndpointView();
	//registerEndpointViewObj.init();
	
	cdrViewObj= new CDRView();
	//cdrViewObj.init();

    historyViewObj = new HistoryView();
	
	networkRouteViewObj=new NetworkRouteView();
	//networkRouteViewObj.init();
	
	confReserveViewObj=new ConfReserveView();
	//confReserveViewObj.init();
	
	//----------------add header text--------------
	cellMCU.setText("<fmt:message key='panel.title.mcu'/>");
	cellConference.setText("<fmt:message key='panel.title.conference'/>");
	cellManageAndView.setText("<fmt:message key='panel.title.manage&view'/>");
	cellConsole.setText("<fmt:message key='panel.title.console'/>");
	cellAddressBook.setText("<fmt:message key='panel.title.addressBook'/>");
	
	//--------------add collapsed text-----------------
	mainLayout.setCollapsedText("d","<fmt:message key='panel.title.console'/>");
	leftLayout.setCollapsedText("a","<fmt:message key='panel.title.conference'/>");
	leftLayout.setCollapsedText("b","<fmt:message key='panel.title.manage&view'/>");
	leftLayout.setCollapsedText("c","<fmt:message key='panel.title.mcu'/>");
	//leftLayout.setCollapsedText("a","<img src=\"<c:url value='/styles/default/images/mcu.gif'/>\" width='18px' height='50px' border='0'>");
	mainLayout.setCollapsedText("c","<img src=\"<c:url value='/styles/default/images/addressBook.gif'/>\" width='18px' height='100px' border='0'>");
	
	//----------------attach online conference------------
	onlineConfObj=new OnlineConf();
	onlineConfObj.init();
	
	menuLinksObj=new MenuLinks();
	menuLinksObj.init();
	
	//--------------------add header-------------------
	mainLayout.attachHeader("id_header");
	
	//---------------------attach event------------------
	leftLayout.attachEvent("onExpand", function(itemId){
	    /*
		if(itemId=="b"||itemId=="c"){
			//cellConference.setHeight(300);
		}else if(itemId=="a"){
			if(!mcuObj){//lazy load
				//attach mcu
				mcuObj=new MCU();
				mcuObj.init();
			}
		}
		*/
	    if(itemId=="c"){
            if(!mcuObj){//lazy load
                //attach mcu
                mcuObj=new MCU();
                mcuObj.init();
            }
        }
	    
	    var list=["a","b","c"];
	    for(var i=0;i<list.length;i++){
	        var name=list[i];
	        if(itemId==name) continue;
	        leftLayout.cells(name).collapse();
	    }
	    
		// Disable tooltip for collapsed Layout cell
		this.cells(itemId).removeAttribute("title");
	});
	
	mainLayout.attachEvent("onExpand",function(itemId){
		if(itemId=="c"){
			confReserveViewObj.resizeScheduler();
			if(!ptcObj){//lazy load
				//attach participant to addressbook cell
				ptcObj=new PTC();
				ptcObj.init();
			}
		}
		// Disable tooltip for collapsed Layout cell
		this.cells(itemId).removeAttribute("title");
	});
	mainLayout.attachEvent("onCollapse",function(itemId){
		if(itemId=="c"){
			confReserveViewObj.resizeScheduler();
		}
		// Disable tooltip for collapsed Layout cell
		this.cells(itemId).removeAttribute("title");
	});
	mainLayout.attachEvent("onPanelResizeFinish", function(){
		confReserveViewObj.resizeScheduler();
	});

	// Disable tooltip for collapsed Layout cell
	leftLayout.attachEvent("onCollapse", function(id){
		this.cells(id).removeAttribute("title");
	});	
	
	ptcObj=new PTC();
	ptcObj.init();
	//---------------collapse cells--------------
	cellAddressBook.collapse();
	cellMCU.collapse();
	cellManageAndView.collapse();
	cellConsole.collapse();
}

function initMenuForConfLevel(){
	var menuData={
			parent: "id_menu",
			onClick:function(id){// click event
				switch (id) {
				case "id_menu_manage_conferenceReservation":
					confReserveViewObj.active();
					break;
				}
			},
			
			items:[{
				id:"id_menu_manage_conferenceReservation",
				text:"<span class='menuitem'><fmt:message key='menu.manage.items.conferenceReservation'/></span>"
			}]
	};
	var menu = new dhtmlXMenuObject(menuData);
	menu.setItemImage("id_menu_manage_conferenceReservation","<c:url value='/styles/default/images/event16.png'/>");
}

function initMenuForSysLevel(){
	var menuData={
			parent: "id_menu",
			onClick:function(id){// click event
				switch (id) {
				case "id_menu_view_registerEndpoints":
					registerEndpointViewObj.active();
					break;
				case "id_menu_manage_user":
					adminViewObj.active();
					break;
                case "id_menu_manage_sipline":
					sipViewObj.active();
					break;
				case "id_menu_manage_conferenceProfile":
					confProfileViewObj.active();
					break;
				case "id_menu_manage_mcu":
					cellMCU.expand();
					break;
				case "id_menu_view_addrssBook":
					cellAddressBook.expand();
					break;
				case "id_menu_view_systemAlerts":
					cellConsole.expand();
					break;
				case "id_menu_manage_participantGroup":
					ptcGroupViewObj.active();
					break;
				case "id_menu_view_version":
					openWin("<fmt:message key='mcu.version.title'/>", "<c:url value='/app/view/mcu/version'/>", 300, 300);
					break;
				case "id_menu_view_systemInfo":
					openWin("<fmt:message key='mcu.statistic.title'/>", "<c:url value='/app/view/mcu/statistic'/>", 402, 580);
					break;
				case "id_menu_view_cdr":
					cdrViewObj.active();
					break;
                case "id_menu_view_history":
					historyViewObj.active();
					break;
				case "id_menu_setup_networkAddress":
					openWin("<fmt:message key='setup.network.address.title'/>", "<c:url value='/app/setup/network/address'/>", 300, 450);
					break;
				case "id_menu_setup_networkRoute":
					networkRouteViewObj.active();
					break;
				case "id_menu_setup_communication":
					openWin("<fmt:message key='setup.mcu.config.header'/>", "<c:url value='/app/setup/mcu/config/enter'/>", 400, 400);
					break;
				case "id_menu_setup_mcuTime":
					openWin("<fmt:message key='setup.dates.header'/>", "<c:url value='/app/setup/dates/enter'/>", 350, 400);
					break;
				case "id_menu_manage_conferenceReservation":
					confReserveViewObj.active();
					break;
				case "id_menu_setup_smtp":
					openWin("<fmt:message key='setup.smtp.header'/>", "<c:url value='/app/setup/smtp'/>", 300, 400);
					break;
				}
			},
			
			items:[{
				id:"id_menu_view",
				text:"<span class='menuitem'><fmt:message key='menu.view'/></span>",
				items:[{
					id:"id_menu_view_registerEndpoints",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.registerEndpoints'/></span>"
				}
				,{
					id:"id_menu_view_cdr",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.cdr'/></span>"
				}
				,{
					id:"id_menu_view_version",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.version'/></span>"
				}
				,{
					id:"id_menu_view_systemInfo",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.systemInfo'/></span>"
				}
                	,{
					id:"id_menu_view_history",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.history'/></span>"
				}
				,{
					id:"id_menu_view_systemAlerts",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.systemAlerts'/></span>"
				}]
			}
			,{
				id:"id_menu_manage",
				text:"<span class='menuitem'><fmt:message key='menu.manage'/></span>",
				items:[{
					id:"id_menu_manage_conferenceProfile",
					text:"<span class='menuitem'><fmt:message key='menu.manage.items.conferenceProfile'/></span>"
				}
				,{
					id:"id_menu_manage_conferenceReservation",
					text:"<span class='menuitem'><fmt:message key='menu.manage.items.conferenceReservation'/></span>"
				}
				,{
					id:"id_menu_manage_mcu",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.mcu'/></span>"
				}
				,{
					id:"id_menu_manage_participantGroup",
					text:"<span class='menuitem'><fmt:message key='menu.manage.items.participantGroup'/></span>"
				}
				,{
					id:"id_menu_manage_user",
					text:"<span class='menuitem'><fmt:message key='menu.manage.items.user'/></span>"
				}
                ,{
					id:"id_menu_manage_sipline",
					text:"<span class='menuitem'><fmt:message key='menu.manage.items.sip'/></span>"
				}
				,{
					id:"id_menu_view_addrssBook",
					text:"<span class='menuitem'><fmt:message key='menu.view.items.addrssBook'/></span>"
				}]
			}
			,{
				id:"id_menu_setup",
				text:"<span class='menuitem'><fmt:message key='menu.setup'/></span>",
				items:[{
					id:"id_menu_setup_networkAddress",
					text:"<span class='menuitem'><fmt:message key='menu.setup.items.networkAddress'/></span>"
				}
				,{
					id:"id_menu_setup_networkRoute",
					text:"<span class='menuitem'><fmt:message key='menu.setup.items.networkRoute'/></span>"
				}
				,{
					id:"id_menu_setup_communication",
					text:"<span class='menuitem'><fmt:message key='menu.setup.items.communication'/></span>"
				}
				,{
					id:"id_menu_setup_mcuTime",
					text:"<span class='menuitem'><fmt:message key='menu.setup.items.mcuTime'/></span>"
				}
				,{
					id:"id_menu_setup_smtp",
					text:"<span class='menuitem'><fmt:message key='menu.setup.items.smtp'/></span>"
				}]
			}]
	};
	var menu = new dhtmlXMenuObject(menuData);
	menu.setItemImage("id_menu_view_registerEndpoints","<c:url value='/styles/default/images/client.png'/>");
	menu.setItemImage("id_menu_view_cdr","<c:url value='/styles/default/images/callTable.png'/>");
	menu.setItemImage("id_menu_view_version","<c:url value='/styles/default/images/version.png'/>");
	menu.setItemImage("id_menu_view_systemInfo","<c:url value='/styles/default/images/sysInfo.png'/>");
	menu.setItemImage("id_menu_view_history","<c:url value='/styles/default/images/connHistory.png'/>");
	menu.setItemImage("id_menu_view_systemAlerts","<c:url value='/styles/default/images/console.png'/>");

	menu.setItemImage("id_menu_manage_conferenceProfile","<c:url value='/styles/default/images/file.png'/>");
	menu.setItemImage("id_menu_manage_conferenceReservation","<c:url value='/styles/default/images/event16.png'/>");
	menu.setItemImage("id_menu_manage_mcu","<c:url value='/styles/default/images/server.png'/>");
	menu.setItemImage("id_menu_manage_participantGroup","<c:url value='/styles/default/images/group.png'/>");
	menu.setItemImage("id_menu_manage_user","<c:url value='/styles/default/images/user.png'/>");
    menu.setItemImage("id_menu_manage_sipline","<c:url value='/styles/default/images/user.png'/>");
	menu.setItemImage("id_menu_view_addrssBook","<c:url value='/styles/default/images/addressbook16.png'/>");

	menu.setItemImage("id_menu_setup_networkAddress","<c:url value='/styles/default/images/iptables.png'/>");
	menu.setItemImage("id_menu_setup_networkRoute","<c:url value='/styles/default/images/table.png'/>");
	menu.setItemImage("id_menu_setup_communication","<c:url value='/styles/default/images/connConf.png'/>");
	menu.setItemImage("id_menu_setup_mcuTime","<c:url value='/styles/default/images/clock-blue.png'/>");
	menu.setItemImage("id_menu_setup_smtp","<c:url value='/styles/default/images/smtp.png'/>");
}
/**
 * create a pop window
 * @param title
 * @param url
 * @param width
 * @param height
 * @param iconEnabled url to the icon for the enabled state
 * @param iconDisabled url to the icon for the disbaled state
 */

function openWin(title,url,width,height,iconEnabled, iconDisabled){
	var w=width||650;
	var h=height||450;

	if(!wins.isWindow("id_pop_win")){
		popwin=wins.createWindow("id_pop_win",0,0,w,h);

		popwin.denyResize();
		popwin.setModal(true);
		popwin.center();
		popwin.button("minmax1").hide();
		popwin.button("minmax2").hide();
		popwin.setText(title);
		popwin.attachURL(url.indexOf("?")!=-1?url+"&__times="+new Date().valueOf():url+"?__times="+new Date().valueOf());
		popwin.setIcon(iconEnabled,iconDisabled); 
		// relative path 
		//wins.setImagePath("<c:url value='/styles/default/images/' />");
	}
}
/**
 * close pop window
 */
function closeWin(){
	if(wins.isWindow("id_pop_win")){
		wins.window("id_pop_win").close();
	}
}
/**
 * active cellContent's view with viewName
 * @param title
 * @param viewName
 * @param loadFunc
 */
function activeCellContent(title,viewName,loadFunc){
	cellContent.showHeader();
	cellContent.setText(title);
	
	cellContent.view(viewName).setActive();
	if(typeof(loadFunc)=="function"){
		loadFunc();
	}
}

/**
 * Set refresh image for layout cells
 * @param cell layout cell
 * @param callback refresh action
 */
function setRefresh(cell,callback){
	if(cell.isHeaderVisible()){
		var $img=$('<img src="<c:url value="/styles/default/images/refresh.png" />" title="<fmt:message key="btn.reload"/>" />').css({
			"cursor":"pointer",
			"vertical-align":"middle"
		});
		if(typeof(callback)== "function")
			$img.click(callback);
		
		var $titleDiv=$(cell).find(".dhtmlxInfoBarLabel");
		$titleDiv.find("img").remove();
		$titleDiv.prepend($img);
	}
}
/**
 * Set grid rows number to cell header the grid was included in
 * @param cell
 * @param total
 */
function setCountTitle(cell,total){
	var $titleDiv=$(cell).find(".dhtmlxInfoBarLabel");
	$titleDiv.find("span.total").remove();
	$titleDiv.append('<span class="total">('+total+')</span>');
}

// ---------------mcu grid---------------
function MCU(){
	var mcuGrid,self=this;
	
	this.init=function(){
		//add toolbar for mcu
		var mcuBar = cellMCU.attachToolbar();
		mcuBar.addButton("id_mcu_btn_new",1,"","<c:url value='/styles/default/images/server_add.png'/>");
		mcuBar.addButton("id_mcu_btn_delete",2,"","<c:url value='/styles/default/images/server_delete.png'/>");
		mcuBar.addButton("id_mcu_btn_modify",3,"","<c:url value='/styles/default/images/server_edit.png'/>");
		mcuBar.addButton("id_mcu_btn_connect",4,"","<c:url value='/styles/default/images/server_go.png'/>");
		// set tooltip
		mcuBar.setItemToolTip("id_mcu_btn_new","<fmt:message key='toolbar.mcu.new'/>");
		mcuBar.setItemToolTip("id_mcu_btn_delete","<fmt:message key='toolbar.mcu.delete'/>");
		mcuBar.setItemToolTip("id_mcu_btn_modify","<fmt:message key='toolbar.mcu.modify'/>");
		mcuBar.setItemToolTip("id_mcu_btn_connect","<fmt:message key='toolbar.mcu.connect'/>");
		
		mcuBar.attachEvent("onClick", function(id){
			if(id=="id_mcu_btn_new"){
				openWin("<fmt:message key='pop.title.mcu.new'/>","<c:url value='/app/manage/mcu'/>?opt=new",450,500,"server_add.png");
			}else if(id=="id_mcu_btn_delete"){
				var ids=mcuGrid.getSelectedRowId();
				if(ids!=null){
					if(ids=="-1"){//whether is the local mcu
						alert(messages.getMsg("mcu.tip.local"));
					}else //if(confirm(messages.getMsg("confirm.tip")))
					{
						//just one id
						self.remove(ids);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_mcu_btn_modify"){
				var ids2=mcuGrid.getSelectedRowId();
				
				if(ids2!=null){
					if(ids2=="-1"){//whether is the local mcu
						//alert(messages.getMsg("mcu.tip.local"));
					}else{
						openWin("<fmt:message key='pop.title.mcu.modify'/>","<c:url value='/app/manage/mcu'/>?opt=modify&id="+ids2,450,500,"server_edit.png");
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_mcu_btn_connect"){
				self.connect();
			}
	    });
		
		mcuGrid = cellMCU.attachGrid();
		mcuGrid.setSkin("${skin}");
		mcuGrid.setHeader([
							"<fmt:message key='grid.mcu.header.name'/>",
							"<fmt:message key='grid.mcu.header.address'/>",
							"<fmt:message key='grid.mcu.header.port'/>",
							"<fmt:message key='grid.mcu.header.user'/>",
							"<fmt:message key='grid.mcu.header.description'/>",
							"pwd"
			                ],null,[
									"text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center"]);
		mcuGrid.setInitWidths("70,100,60,80,80,0");
		mcuGrid.setColTypes("ro,ro,ro,ro,ro,ro");
		mcuGrid.setColSorting("str,str,str,str,str,str");
		mcuGrid.enableTooltips("fales,fales,fales,fales,fales,fales");
		mcuGrid.setStyle("","","","font-weight:bold;");
		mcuGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");

		mcuGrid.attachEvent("onRowDblClicked", function(rId,cInd){
			self.connect();
		});
		mcuGrid.init();
		
		self.reload();
		
		setRefresh(cellMCU,function(){
			self.reload();
		});
	};
	
	this.reload=function(){
		$.wmapp.perm(function(){
			cellMCU.progressOn();
			mcuGrid.clearAll();
			mcuGrid.load("<c:url value='/app/manage/mcu/list/json'/>",self.load_callback,"json");
		});
	};

	this.load_callback=function(){
        cellMCU.progressOff();
		setCountTitle(cellMCU, mcuGrid.getRowsNum());
    };
	
	this.remove=function(id){
		$.ajax({
			url:"<c:url value='/app/manage/mcu/'/>"+id,
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};
	
	this.connect=function(){
		var selId=mcuGrid.getSelectedRowId();
		
		if(selId!=null){
			if(selId=="-1"){//local
				$.ajax({
					url:"<c:url value='/app/perm/connect/local' />",
					type:"GET",
					data:{
						"times":new Date().valueOf()
					},
					success:function(data){
						var ret=$.parseJSON(data);
						if(ret.success=="true"){
							location.href="<c:url value='/app/manage/main' />";
						}else if(ret.msg){
							alert(ret.msg);
						}
					}
				});
			}else{//remote
				$.ajax({
					url:"<c:url value='/app/perm/connect' />",
					type:"POST",
					data:{
						"times":new Date().valueOf(),
						"mcuid":selId
					},
					success:function(data){
						var ret=$.parseJSON(data);
						if(ret.success=="true"){
							location.href="<c:url value='/app/manage/main' />";
						}else if(ret.msg){
							alert(ret.msg);
						}
					}
				});
			}
		}else{
			//alert(messages.getMsg("noSelect.tip"));
		}
	};
}
//--------------------administrator(System user)---------------
// Define the constructor
function AdminView(){
	var adminGrid,self=this,V_ADMIN="v_admin",inited=false;

	this.init=function(){               
		//add toolbar for user
		var adminBar = cellContent.view(V_ADMIN).attachToolbar();
		adminBar.addButton("id_admin_btn_new",1,"","<c:url value='/styles/default/images/user_add.png'/>");
		adminBar.addButton("id_admin_btn_delete",2,"","<c:url value='/styles/default/images/user_remove.png'/>");
		adminBar.addButton("id_admin_btn_modify",3,"","<c:url value='/styles/default/images/user_edit.png'/>");
		// set tooltip
		adminBar.setItemToolTip("id_admin_btn_new","<fmt:message key='toolbar.user.new'/>");
		adminBar.setItemToolTip("id_admin_btn_delete","<fmt:message key='toolbar.user.delete'/>");
		adminBar.setItemToolTip("id_admin_btn_modify","<fmt:message key='toolbar.user.modify'/>");

		adminBar.addInput("id_admin_input_filter",4,"",100);
		adminBar.setItemToolTip("id_admin_input_filter","<fmt:message key='toolbar.user.filtertext'/>");
		
		adminBar.addButton("id_admin_btn_filter",5,"","<c:url value='/styles/default/images/search.png'/>");
		adminBar.setItemToolTip("id_admin_btn_filter","<fmt:message key='toolbar.user.filter'/>");

		adminBar.attachEvent("onClick", function(id){
			if(id=="id_admin_btn_new"){
				openWin("<fmt:message key='pop.title.admin.new'/>","<c:url value='/app/manage/admin'/>?opt=new",500,400,"user_add.png");
			}else if(id=="id_admin_btn_delete"){
				var names=adminGrid.getSelectedRowId();
				
				if(names){
					if((","+names+",").indexOf(",root,")!=-1){//root user cannot remove
						alert(messages.getMsg("admin.tip.root.remove"));
					}else //if(confirm(messages.getMsg("confirm.tip")))
					{
						self.remove(names);
					}
				}else{
					alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_admin_btn_modify"){
				self.onClickModify();
			}else if(id=="id_admin_btn_filter"){
				adminGrid.filterBy(0,adminBar.getValue("id_admin_input_filter"));
			}
		});

		adminBar.attachEvent("onEnter", function(id, value){
		    if(id == "id_admin_input_filter")
			adminGrid.filterBy(0,value);
		});
		
		// attach admin grid in cellCentent
		adminGrid = cellContent.view(V_ADMIN).attachGrid();          
		adminGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		adminGrid.setHeader([
							"<fmt:message key='grid.admin.header.name'/>",
							"<fmt:message key='grid.admin.header.realname'/>",
							"<fmt:message key='grid.admin.header.phone'/>",
							"<fmt:message key='grid.admin.header.email'/>",
							"<fmt:message key='grid.admin.header.address'/>",
							"<fmt:message key='grid.admin.header.accesslevel'/>",
							//"<fmt:message key='grid.admin.header.grouplimit'/>",
							"<fmt:message key='grid.admin.header.group'/>"
			                ],null,[
			                        "text-align:center",
			                     	"text-align:center",
			                     	"text-align:center",
				                 	"text-align:center",
				               		"text-align:center",
				            		"text-align:center",
				            		//"text-align:center",
			                        "text-align:center"]);
		adminGrid.setInitWidths("80,100,*,*,*,80,80");
		adminGrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro");
		adminGrid.setSkin("${skin}");
		//adminGrid.enableMultiselect(true);
		adminGrid.setColSorting("str,str,str,str,str,str");
		adminGrid.enableTooltips("fales,fales,fales,fales,fales,fales,false");
		adminGrid.setStyle("","","","font-weight:bold;");
		adminGrid.init();
                
		//grid dblclick event attach
		adminGrid.attachEvent("onRowDblClicked", function(rId,cInd){
		    self.onClickModify();
		});
		
		inited=true;
	};
	
	this.reload=function(){
        cellContent.progressOn();
        adminGrid.clearAll();
        adminGrid.load("<c:url value='/app/manage/admin/list/json'/>",self.load_callback,"json");
    	//adminGrid.clearAndLoad("<c:url value='/app/manage/admin/list/json'/>","json");
	};

    this.onClickModify=function(){
        var names=adminGrid.getSelectedRowId();
        if(names){
            if(names.indexOf(",")!=-1){
                //alert(messages.getMsg("oneSelect.tip"));
            }else if((","+names+",").indexOf(",root,")!=-1&&"${sessionScope.loginInfo.username}"!="root"){
                alert(messages.getMsg("admin.tip.root.modify"));
            }else{
                openWin("<fmt:message key='pop.title.admin.modify'/>","<c:url value='/app/manage/admin'/>?opt=modify&name="+encodeURI(names),500,400,"user_edit.png");
            }
        }else{
            //alert(messages.getMsg("noSelect.tip"));
        }
    };

    this.load_callback=function(){
        cellContent.progressOff();
    };
	
	this.remove=function(names){
		$.ajax({
			url:"<c:url value='/app/manage/admin/'/>"+encodeURI(names),
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};
	
	this.active=function(){
		if(!inited)
			this.init();
		
		activeCellContent("<fmt:message key='menu.manage.items.user'/>",V_ADMIN,function(){
			self.reload();
		});
		setRefresh(cellContent, function(){
			self.reload();
		});
	};
}

//--------------------SIP Account ---------------
function SipView(){
	var sipGrid,self=this,V_SIP="v_sip",inited=false;

	this.init=function(){
		//add toolbar for user
		var sipBar = cellContent.view(V_SIP).attachToolbar();
		sipBar.addButton("id_sip_btn_new",1,"","<c:url value='/styles/default/images/user_add.png'/>");
		sipBar.addButton("id_sip_btn_delete",2,"","<c:url value='/styles/default/images/user_remove.png'/>");
		sipBar.addButton("id_sip_btn_modify",3,"","<c:url value='/styles/default/images/user_edit.png'/>");
		// set tooltip
		sipBar.setItemToolTip("id_sip_btn_new","<fmt:message key='toolbar.sip.new'/>");
		sipBar.setItemToolTip("id_sip_btn_delete","<fmt:message key='toolbar.sip.delete'/>");
		sipBar.setItemToolTip("id_sip_btn_modify","<fmt:message key='toolbar.sip.modify'/>");

		sipBar.addInput("id_sip_input_filter",4,"",100);
		sipBar.setItemToolTip("id_sip_input_filter","<fmt:message key='toolbar.sip.filtertext'/>");

		sipBar.addButton("id_sip_btn_filter",5,"","<c:url value='/styles/default/images/search.png'/>");
		sipBar.setItemToolTip("id_sip_btn_filter","<fmt:message key='toolbar.sip.filter'/>");

		sipBar.attachEvent("onClick", function(id){
			if(id=="id_sip_btn_new"){
				openWin("<fmt:message key='pop.title.sip.new'/>","<c:url value='/app/manage/sip'/>?opt=new",500,400,"user_add.png");
			}else if(id=="id_sip_btn_delete"){
				var names=sipGrid.getSelectedRowId();

				if(names){
					self.remove(names);
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_sip_btn_modify"){
				self.onClickModify();
			}else if(id=="id_sip_btn_filter"){
				sipGrid.filterBy(0,sipBar.getValue("id_sip_input_filter"));
			}
		});

		sipBar.attachEvent("onEnter", function(id, value){
		    if(id == "id_sip_input_filter")
			sipGrid.filterBy(0,value);
		});

		// attach admin grid in cellCentent
		sipGrid = cellContent.view(V_SIP).attachGrid();
		sipGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		sipGrid.setHeader([
							"<fmt:message key='grid.sip.header.account'/>",
							"<fmt:message key='grid.sip.header.enabled'/>",
							"<fmt:message key='grid.sip.header.username'/>",
							"<fmt:message key='grid.sip.header.authname'/>",
							"<fmt:message key='grid.sip.header.registrar'/>",
                            "<fmt:message key='grid.sip.header.domain'/>",
							"<fmt:message key='grid.sip.header.status'/>",
                            "<fmt:message key='grid.sip.header.reason'/>"
			                ],null,[
			                        "text-align:center",
			                     	"text-align:center",
			                     	"text-align:center",
				                 	"text-align:center",
                                    "text-align:center",
				               		"text-align:center",
                                    "text-align:center",
			                        "text-align:center"]);
		sipGrid.setInitWidths("100,40,80,80,120,80,60,120");
		sipGrid.setColTypes("ro,ch,ro,ro,ro,ro,ro,ro");
		sipGrid.setSkin("${skin}");
	
		sipGrid.setColSorting("str,str,str,str,str,str,str,str");
		sipGrid.enableTooltips("fales,fales,fales,fales,fales,false,false,false");
        sipGrid.setColAlign("left,center,left,left,left,left,center,left");		
        sipGrid.setStyle("","","","font-weight:bold;");
		sipGrid.init();

		//grid dblclick event attach
		sipGrid.attachEvent("onRowDblClicked", function(rId,cInd){
		    self.onClickModify();
		});

		inited=true;
	};

	this.reload=function(){
        cellContent.progressOn();
        sipGrid.clearAll();
        sipGrid.load("<c:url value='/app/manage/sip/list/json'/>",self.load_callback,"json");
	};

    this.onClickModify=function(){
        var names=sipGrid.getSelectedRowId();
        if(names){
            if(names.indexOf(",")!=-1){
               
            }else{
                openWin("<fmt:message key='pop.title.sip.modify'/>","<c:url value='/app/manage/sip'/>?opt=modify&name="+encodeURI(names),500,400,"user_edit.png");
            }
        }else{
            
        }
    };

    this.load_callback=function(){
        self.parseImgTitle();
        cellContent.progressOff();
    };

	this.remove=function(names){
		$.ajax({
			url:"<c:url value='/app/manage/sip/'/>"+encodeURI(names),
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){				
				self.reload();
			}
		});
	};

	this.active=function(){
		if(!inited)
			this.init();

		activeCellContent("<fmt:message key='menu.manage.items.sip'/>",V_SIP,function(){
			self.reload();
		});
		setRefresh(cellContent, function(){
			self.reload();
		});
	};

    this.parseImgTitle=function(){
    	//$(cellContent.view(V_SIP)).find("span[title^='$']").each(function(){
        $(cellContent).find("span[title^='$']").each(function(){
			parseElementTitle(this);
		});
    };
}

//------------------------Register endpoint view ---------------------
function RegisterEndpointView(){
	var regEndpointsGrid,self=this,V_REG_ENDPOINTS="v_reg_endpoints",inited=false;
	
	this.init=function(){
		regEndpointsGrid=cellContent.view(V_REG_ENDPOINTS).attachGrid();
		regEndpointsGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		regEndpointsGrid.setHeader([
							"<fmt:message key='grid.view.participant.number'/>",
							"<fmt:message key='grid.view.participant.name'/>",
							"<fmt:message key='grid.view.participant.driver'/>",
							"<fmt:message key='grid.view.participant.incallImg'/>",
							"<fmt:message key='grid.view.participant.data'/>"
			                ],null,[
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center"
			                     ]);
		regEndpointsGrid.setInitWidths("100,120,80,80,*");
		regEndpointsGrid.setColTypes("ro,ro,ro,ro,ro");
		regEndpointsGrid.setColSorting("str,str,str,str,str");
		regEndpointsGrid.enableTooltips("fales,fales,fales,fales,fales");
		regEndpointsGrid.setStyle("","","","font-weight:bold;");
		regEndpointsGrid.setSkin("${skin}");
		regEndpointsGrid.init();
		
		inited=true;
	};
	
	this.reload=function(){
		cellContent.progressOn();
		regEndpointsGrid.clearAll();
		regEndpointsGrid.load("<c:url value='/app/view/participants'/>",self.load_callback,"json");
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		activeCellContent("<fmt:message key='view.participants.title'/>",V_REG_ENDPOINTS,function(){
			self.reload();
		});
		setRefresh(cellContent, function(){
			self.reload();
		});
	};

	this.load_callback=function(){
		cellContent.progressOff();
	};
}

//----------------ParticipantGroup-----------------
function PTCGroupView(){
	var participantGroupGrid,self=this,V_PARTICIPANT_GROUP="v_participant_group",inited=false;
	
	this.init=function(){
		var participantGroupBar = cellContent.view(V_PARTICIPANT_GROUP).attachToolbar();
		participantGroupBar.addButton("id_participantGroup_btn_new",1,"","<c:url value='/styles/default/images/group_add.png'/>");
		participantGroupBar.addButton("id_participantGroup_btn_delete",2,"","<c:url value='/styles/default/images/group_remove.png'/>");
		participantGroupBar.addButton("id_participantGroup_btn_modify",3,"","<c:url value='/styles/default/images/group_edit.png'/>");
		// set tooltip
		participantGroupBar.setItemToolTip("id_participantGroup_btn_new","<fmt:message key='toolbar.group.new'/>");
		participantGroupBar.setItemToolTip("id_participantGroup_btn_delete","<fmt:message key='toolbar.group.delete'/>");
		participantGroupBar.setItemToolTip("id_participantGroup_btn_modify","<fmt:message key='toolbar.group.modify'/>");
		
		participantGroupBar.attachEvent("onClick", function(id){
			if(id=="id_participantGroup_btn_new"){
				openWin("<fmt:message key='pop.title.group.new'/>","<c:url value='/app/manage/group'/>?opt=new",400,300,"group_add.png");
			}else if(id=="id_participantGroup_btn_delete"){
				var keys=participantGroupGrid.getSelectedRowId();
				
				if(keys){
					if(confirm(messages.getMsg("group.confirm.tip"))){
						self.remove(keys);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_participantGroup_btn_modify"){
				self.onClickModify();
			}
		});
		
		participantGroupGrid = cellContent.view(V_PARTICIPANT_GROUP).attachGrid();
		participantGroupGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		participantGroupGrid.setHeader([
							"<fmt:message key='grid.group.header.name'/>",
							"<fmt:message key='grid.group.header.description'/>"
			                ],null,[
			                        "text-align:center",
			                        "text-align:center"]);
		participantGroupGrid.setInitWidths("100,*");
		participantGroupGrid.setSkin("${skin}");
		participantGroupGrid.setColTypes("ro,ro");
		participantGroupGrid.setColSorting("str,str");
		participantGroupGrid.enableTooltips("fales,fales");
		participantGroupGrid.setStyle("","","","font-weight:bold;");
		participantGroupGrid.init();

		// Attach grid dblclick event
		participantGroupGrid.attachEvent("onRowDblClicked", function(rId,cInd){
		    self.onClickModify();
		});
		
		inited=true;
	};

	this.onClickModify=function(){
		var key=participantGroupGrid.getSelectedRowId();
		if(key){
			openWin("<fmt:message key='pop.title.group.modify'/>","<c:url value='/app/manage/group'/>?opt=modify&key="+encodeURI(key),400,300,"group_edit.png");
		}else{
			//alert(messages.getMsg("noSelect.tip"));
		}
	};
	
	this.remove=function(keys){
		$.ajax({
			url:"<c:url value='/app/manage/group/'/>"+encodeURI(keys),
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
				ptcObj.reload();
			}
		});
	};
	
	this.reload=function(){
		cellContent.progressOn();
        participantGroupGrid.clearAll();
        participantGroupGrid.load("<c:url value='/app/manage/group/list/json'/>",self.load_callback,"json");
		//participantGroupGrid.clearAndLoad("<c:url value='/app/manage/group/list/json'/>","json");
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		activeCellContent("<fmt:message key='menu.manage.items.group'/>",V_PARTICIPANT_GROUP,function(){
			self.reload();
		});
		setRefresh(cellContent, function(){
			self.reload();
		});
	};

	this.load_callback=function(){
        cellContent.progressOff();
    };
}

//----------------Participant(Address Book)-----------------
function PTC(){
	var participantGrid,self=this;
	
	this.init=function(){
		var participantBar = cellAddressBook.attachToolbar();
		participantBar.addButton("id_participant_btn_new",1,"","<c:url value='/styles/default/images/addressbook-add.png'/>");
		participantBar.addButton("id_participant_btn_delete",2,"","<c:url value='/styles/default/images/addressbook-remove.png'/>");
		participantBar.addButton("id_participant_btn_modify",3,"","<c:url value='/styles/default/images/addressbook-edit.png'/>");
		// set tooltip
		participantBar.setItemToolTip("id_participant_btn_new","<fmt:message key='toolbar.addressbook.new'/>");
		participantBar.setItemToolTip("id_participant_btn_delete","<fmt:message key='toolbar.addressbook.delete'/>");
		participantBar.setItemToolTip("id_participant_btn_modify","<fmt:message key='toolbar.addressbook.modify'/>");
		
		participantBar.addInput("id_group_filter",4,"",50);
		participantBar.setItemToolTip("id_group_filter","<fmt:message key='inputGroup'/>");
		
		participantBar.addInput("id_participant_input_filter",5,"",80);
		participantBar.setItemToolTip("id_participant_input_filter","<fmt:message key='toolbar.addressbook.filtertext'/>");

		participantBar.addButton("id_participant_btn_search",6,"","<c:url value='/styles/default/images/search.png'/>");
		participantBar.setItemToolTip("id_participant_btn_search","<fmt:message key='toolbar.addressbook.filter'/>");

		participantBar.attachEvent("onEnter", function(id, value){
		    if(id == "id_participant_input_filter"||id=="id_group_filter"){
		    	participantGrid.filterBy(1,participantBar.getValue("id_participant_input_filter"));
				participantGrid.filterBy(3,participantBar.getValue("id_group_filter"),true);
		    }
		});
		
		participantBar.attachEvent("onClick", function(id){
			if(id=="id_participant_btn_new"){
				openWin("<fmt:message key='pop.title.participant.new'/>","<c:url value='/app/manage/participant'/>?opt=new",500,450,"addressbook-add.png");
			}else if(id=="id_participant_btn_delete"){
				var keys=participantGrid.getSelectedRowId();
				
				if(keys){
					//if(confirm(messages.getMsg("confirm.tip")))
					{
						self.remove(keys);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_participant_btn_modify"){
				self.onClickModify();
			}else if(id=="id_participant_btn_search"){
				participantGrid.filterBy(1,participantBar.getValue("id_participant_input_filter"));
				participantGrid.filterBy(3,participantBar.getValue("id_group_filter"),true);
			}
		});
		
		participantGrid = cellAddressBook.attachGrid();
		participantGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		participantGrid.setHeader([
							"<fmt:message key='grid.participant.header.number'/>",
							"<fmt:message key='grid.participant.header.name'/>",
							"<fmt:message key='grid.participant.header.states'/>",
							"<fmt:message key='grid.participant.header.group'/>",
							"<fmt:message key='grid.participant.header.bandwidth'/>",
							"<fmt:message key='grid.participant.header.ip'/>"
			                ],null,[
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center"]);
		participantGrid.setInitWidths("70,90,60,80,70,100");
		participantGrid.setColSorting("str,str,na,str,int,str");
		participantGrid.setColTypes("ro,ro,ro,ro,ro,ro");
		participantGrid.enableMultiselect(true);
		participantGrid.enableDragAndDrop(true);
		participantGrid.enableTooltips("fales,fales,fales,fales,fales,fales");
		participantGrid.setColAlign("left,left,center,left,center,left");
		participantGrid.setStyle("","","","font-weight:bold;");
		//participantGrid.enableAlterCss("even", "uneven");

		participantGrid.rowToDragElement=function(id){
			//var text = participantGrid._dragged.length + messages.getMsg("participant.drap.tip");
			//return text;
			var selectRows=participantGrid.getSelectedRowId();
			if(selectRows!=null){
				return selectRows.split(',').length+' '+messages.getMsg("participant.drap.tip");
			}else
				return messages.getMsg("noSelect.tip");
	    };

	    //Make this grid do not support drag in
	    participantGrid.attachEvent("onDrag", function(sId,tId,sObj,tObj,sInd,tInd){
	    	return false;
	    });

		//Grid dblclick event attach
		participantGrid.attachEvent("onRowDblClicked", function(rId,cInd){
		    self.onClickModify();
		});
		
	    participantGrid.setSkin("${skin}");
		participantGrid.init();
		
		self.reload();
		
		setRefresh(cellAddressBook, function(){
			self.reload();
		});
		
		//Interval refresh
        //地址簿刷新时间
		setInterval(function(){
			self.reload();
		},33*1000);
	};
	
	this.reload=function(){
		cellAddressBook.progressOn();
		participantGrid.clearAll();
		participantGrid.load("<c:url value='/app/manage/participant/list/json'/>", self.load_callback,"json");
	};
	
	this.remove=function(keys){
		$.ajax({
			url:"<c:url value='/app/manage/participant/'/>"+encodeURI(keys),
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};

	this.onClickModify=function(){
		var key=participantGrid.getSelectedRowId();
		if(key){
			if(key.indexOf(",")!=-1){
				//alert(messages.getMsg("oneSelect.tip"));
			}else{
				openWin("<fmt:message key='pop.title.participant.modify'/>","<c:url value='/app/manage/participant'/>?opt=modify&key="+encodeURI(key),500,450,"addressbook-edit.png");
			}
		}else{
			//alert(messages.getMsg("noSelect.tip"));
		}
	};

	this.load_callback=function(){
		self.parseImgTitle();
		setCountTitle(cellAddressBook, participantGrid.getRowsNum());
        cellAddressBook.progressOff();
    };
    
    this.parseImgTitle=function(){
    	$(cellAddressBook).find("span[title^='$']").each(function(){
			parseElementTitle(this);
		});
    };
}

//----------------ConfProfile-----------------
function ConfProfileView(){
	var confProfileGrid,self=this,V_CONF_PROFILE="v_conf_profile",inited=false;
	
	this.init=function(){
		var confProfileBar = cellContent.view(V_CONF_PROFILE).attachToolbar();
		confProfileBar.addButton("id_confProfile_btn_new",1,"","<c:url value='/styles/default/images/file_add.png'/>");
		confProfileBar.addButton("id_confProfile_btn_delete",2,"","<c:url value='/styles/default/images/file_delete.png'/>");
		confProfileBar.addButton("id_confProfile_btn_modify",3,"","<c:url value='/styles/default/images/file_edit.png'/>");
		// set tooltip
		confProfileBar.setItemToolTip("id_confProfile_btn_new","<fmt:message key='toolbar.profile.new'/>");
		confProfileBar.setItemToolTip("id_confProfile_btn_delete","<fmt:message key='toolbar.profile.delete'/>");
		confProfileBar.setItemToolTip("id_confProfile_btn_modify","<fmt:message key='toolbar.profile.modify'/>");
		
		confProfileBar.attachEvent("onClick", function(id){
			if(id=="id_confProfile_btn_new"){
				openWin("<fmt:message key='pop.title.profile.new'/>","<c:url value='/app/manage/profile'/>?opt=new",600,500,"file_add.png");
			}else if(id=="id_confProfile_btn_delete"){
				var keys=confProfileGrid.getSelectedRowId();
				
				if(keys){
					//if(confirm(messages.getMsg("confirm.tip")))
					{
						self.remove(keys);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}else if(id=="id_confProfile_btn_modify"){
				self.onClickModify();
			}
		});
		
		confProfileGrid = cellContent.view(V_CONF_PROFILE).attachGrid();
		confProfileGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		confProfileGrid.setHeader([
									"<fmt:message key='grid.profile.header.name'/>",
									"<fmt:message key='grid.profile.header.bandwidth'/>",
									"<fmt:message key='grid.profile.header.definition'/>",
									"<fmt:message key='grid.profile.header.updateTime'/>",
									"<fmt:message key='grid.profile.header.description'/>"
			                ],null,[
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center"]);
		confProfileGrid.setInitWidths("150,100,100,150,*");
		confProfileGrid.setSkin("${skin}");
		confProfileGrid.setColTypes("ro,ro,ro,ro,ro");
		confProfileGrid.setColSorting("str,int,str,date,na");
		confProfileGrid.enableTooltips("fales,fales,fales,fales,false");
		confProfileGrid.setStyle("","","","font-weight:bold;");
		//confProfileGrid.enableMultiselect(true);
		confProfileGrid.init();

		// Attach grid dblclick event
		confProfileGrid.attachEvent("onRowDblClicked", function(rId,cInd){
		    self.onClickModify();
		});
		
		inited=true;
	};
	
	this.reload=function(){
		cellContent.progressOn();
		confProfileGrid.clearAll();
		confProfileGrid.load("<c:url value='/app/manage/profile/list/json'/>",self.load_callback,"json");
		//confProfileGrid.clearAndLoad("<c:url value='/app/manage/profile/list/json'/>","json");
	};

	this.onClickModify=function(){
		var key=confProfileGrid.getSelectedRowId();
		if(key){
			if(key.indexOf(",")!=-1){
				//alert(messages.getMsg("oneSelect.tip"));
			}else{
				openWin("<fmt:message key='pop.title.profile.modify'/>","<c:url value='/app/manage/profile'/>?opt=modify&key="+encodeURI(key),600,500,"file_edit.png");
			}
		}else{
			//alert(messages.getMsg("noSelect.tip"));
		}
	};

	this.load_callback=function(){
		cellContent.progressOff();
	};
	
	this.remove=function(keys){
		$.ajax({
			url:"<c:url value='/app/manage/profile/'/>"+encodeURI(keys),
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		activeCellContent("<fmt:message key='menu.manage.items.conferenceProfile'/>",V_CONF_PROFILE,function(){
			self.reload();
		});
		
		setRefresh(cellContent, function(){
			self.reload();
		});
	};
}
//----------------Online conference-----------------
function OnlineConf(){
	var conferenceGrid,self=this;
	
	this.init=function(){
	    var onlineConferenceBar = cellConference.attachToolbar();
        //onlineConferenceBar.setSkin("${skin}");
        onlineConferenceBar.addButton("id_conference_btn_new",1,"","<c:url value='/styles/default/images/add16.png'/>");
        onlineConferenceBar.addButton("id_conference_btn_delete",2,"","<c:url value='/styles/default/images/delete16.png'/>");
        onlineConferenceBar.addButton("id_conference_btn_modify",3,"","<c:url value='/styles/default/images/edit16.png'/>");
        onlineConferenceBar.addButton("id_conference_btn_control",4,"","<c:url value='/styles/default/images/tools.gif'/>");
        onlineConferenceBar.addButton("id_conference_btn_pause",5,"","<c:url value='/styles/default/images/pause_blue.png'/>");
        onlineConferenceBar.addButton("id_conference_btn_restart",6,"","<c:url value='/styles/default/images/restart.png'/>");

        // set tooltip
        onlineConferenceBar.setItemToolTip("id_conference_btn_new","<fmt:message key='toolbar.onlineConference.new'/>");
        onlineConferenceBar.setItemToolTip("id_conference_btn_delete","<fmt:message key='toolbar.onlineConference.delete'/>");
        onlineConferenceBar.setItemToolTip("id_conference_btn_modify","<fmt:message key='toolbar.onlineConference.modify'/>");
        onlineConferenceBar.setItemToolTip("id_conference_btn_control","<fmt:message key='toolbar.onlineConference.control'/>");
        onlineConferenceBar.setItemToolTip("id_conference_btn_pause","<fmt:message key='toolbar.onlineConference.pause'/>");
        onlineConferenceBar.setItemToolTip("id_conference_btn_restart","<fmt:message key='toolbar.onlineConference.restart'/>");
        
        onlineConferenceBar.attachEvent("onClick", function(id){
            var key;
            if(id=="id_conference_btn_new"){
                openWin("<fmt:message key='pop.title.conference.new'/>","<c:url value='/app/manage/conf'/>?opt=new",650,550,"add16.png");
            }else if(id=="id_conference_btn_delete"){
                key=conferenceGrid.getSelectedRowId();              
                if(key){
                    if(confirm(messages.getMsg("confirm.endConf"))){
                        self.remove(key);
                    }
                }else{
                    //alert(messages.getMsg("noSelect.tip"));
                }
            }else if(id=="id_conference_btn_modify"){
                key=conferenceGrid.getSelectedRowId();
                if(key){
                    openWin("<fmt:message key='pop.title.conference.modify'/>","<c:url value='/app/manage/conf'/>?opt=modify&key="+encodeURI(key),650,550,"edit16.png");
                }else{
                    //alert(messages.getMsg("noSelect.tip"));
                }
            }else if(id=="id_conference_btn_control"){
                key=conferenceGrid.getSelectedRowId();
                if(key){
                    selectedConfNumber=key;
                    confCtrlViewObj.active();
                }else{
                    //alert(messages.getMsg("noSelect.tip"));
                }
            }else if(id=="id_conference_btn_pause"){
                key=conferenceGrid.getSelectedRowId();
                if(key){
                     if(confirm(messages.getMsg("confirm.pauseConf"))){
                     self.pause(key);
                    }
                }else{
                    //alert(messages.getMsg("noSelect.tip"));
                }
            }else if(id=="id_conference_btn_restart"){
                key=conferenceGrid.getSelectedRowId();
                if(key){
                     self.restart(key);
                }else{
                    //alert(messages.getMsg("noSelect.tip"));
                }
            }
        });
        
		conferenceGrid=cellConference.attachGrid();
		conferenceGrid.setSkin("${skin}");
		conferenceGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		conferenceGrid.setHeader([
						"",
						"<fmt:message key='grid.onlineConference.header.id'/>",
						"<fmt:message key='grid.onlineConference.header.name'/>",						
						"<fmt:message key='grid.onlineConference.header.participants'/>",
						"<fmt:message key='grid.onlineConference.header.group'/>",
                        "<fmt:message key='grid.onlineConference.header.endTime'/>"
		                ],null,[
                                "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center"]);
		conferenceGrid.setInitWidths("26,60,80,60,90,100");
		conferenceGrid.setColTypes("ro,ro,ro,ro,ro,ro");
		conferenceGrid.setColSorting("str,str,str,date,str,str");
		conferenceGrid.enableTooltips("false,fales,fales,fales,fales,fales");
		conferenceGrid.setColAlign("center,left,left,center,left");
		conferenceGrid.setStyle("","","","font-weight:bold;");

		conferenceGrid.attachEvent("onRowDblClicked", function(rid,cindex){
			selectedConfNumber=rid;
			confCtrlViewObj.active();
		});
		
		conferenceGrid.init();
		self.reload();
		
		setRefresh(cellConference, function(){
			self.reload();
		});
		
		//Interval refresh
        // 会议列表刷新
		setInterval(function(){
			self.reload();
		},63*1000);
	};
	
	this.reload=function(){
		$.wmapp.perm(function(){
			cellConference.progressOn();
			conferenceGrid.clearAll();
			conferenceGrid.load("<c:url value='/app/manage/conf/list/json'/>",self.load_callback,"json");
		});
	};

	this.load_callback=function(){
		cellConference.progressOff();
		setCountTitle(cellConference, conferenceGrid.getRowsNum());
	};
	
	this.remove=function(keys){
		$.ajax({
			url:"<c:url value='/app/manage/conf/'/>"+encodeURI(keys),
			type:"POST",
			data:{
				_method:"DELETE",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};
        this.pause=function(keys){
		$.ajax({
			url:"<c:url value='/app/manage/conf/pause/'/>"+encodeURI(keys),
			type:"POST",
			data:{
				_method:"PUT",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};

        this.restart=function(keys){
		$.ajax({
			url:"<c:url value='/app/manage/conf/restart/'/>"+encodeURI(keys),
			type:"POST",
			data:{
				_method:"PUT",
				times:new Date().valueOf()
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};
}
//----------------------Online conference control---------------------
function ConfCtrlView(){
	var confCtrlTabbar,confCtrlPtcToolbar,confCtrlPtcGrid,self=this,V_CONF_CONTROL="v_conf_control",broadcastGrid,confStatus,inited=false;
	var firstTimeInitLayout, firstTimeInitConfInfo,firstTimeInitSendMsg,firstTimeInitDebugInfo,firstTimeInitBroadcastInfo;
	this.init=function(){
		
		confCtrlTabbar=cellContent.view(V_CONF_CONTROL).attachTabbar();
		confCtrlTabbar.setImagePath("<c:url value='/styles/dhx2/${style}/imgs/'/>");
		
		confCtrlTabbar.addTab("id_tab_participant","<fmt:message key='tab.common.items.participants'/>","80px");
		confCtrlTabbar.addTab("id_tab_layout","<fmt:message key='tab.common.items.layout'/>","80px");
		confCtrlTabbar.addTab("id_tab_sendMsg","<fmt:message key='tab.common.items.sendMsg'/>","80px");
		confCtrlTabbar.addTab("id_tab_confInfo","<fmt:message key='tab.common.items.confInfo'/>","80px");
		confCtrlTabbar.addTab("id_tab_broadcast","<fmt:message key='tab.common.items.broadcast'/>","80px");
		confCtrlTabbar.addTab("id_tab_debug","<fmt:message key='tab.common.items.debug'/>","80px");
		
		//confCtrlTabbar.setTabActive("id_tab_participant");
		confCtrlTabbar.enableAutoReSize(true,true);
		//confCtrlTabbar.setSkinColors("#FFFF00", "#FFFACD");
		this.initParticipantsTab();
		this.initLayoutTab();
		this.initInfoTab();
		this.initSendMessageTab();
		this.initDebugTab();
		this.initBroadcastTab();
		
		this.intervalRefreshPTC();
        confCtrlTabbar.attachEvent("onSelect", function(id,last_id){
              //any custom code
              if(id == "id_tab_layout")  {
                  if(firstTimeInitLayout) {
                    self.reloadLayout();
                    firstTimeInitLayout = false;
                  }
                  //alert(id);
              }
              else if(id == "id_tab_sendMsg"){
                  if(firstTimeInitSendMsg) {
                     self.initSendMsg();
                     firstTimeInitSendMsg = false;
                  }
              }
              else if(id == "id_tab_confInfo"){
                  if(firstTimeInitConfInfo) {
                     self.initConfInfo();
                     firstTimeInitConfInfo = false;
                  }
              }else if(id == "id_tab_broadcast"){
                  if(firstTimeInitBroadcastInfo) {
                    self.reloadBroadcast();
                    firstTimeInitBroadcastInfo = false;
                  }
              }else if(id == "id_tab_debug"){
                  if(firstTimeInitDebugInfo) {
                    self.initDebugInfo();
                    firstTimeInitDebugInfo = false;
                  }
              }
              return true;
          });
		
		inited=true;
	};
	
	//Auto refresh participants tab per 60 seconds
    //会议控制与会者刷新
	this.intervalRefreshPTC=function(){
		setInterval(function(){
			if(selectedConfNumber!=null&&confCtrlTabbar.getActiveTab()=="id_tab_participant"){
				$("div").remove(".bigimg");//clear big snap shot image
				self.reloadValues();
			}
		},17*1000);

        setInterval(function(){
			if(selectedConfNumber!=null&&confCtrlTabbar.getActiveTab()=="id_tab_broadcast"){
				//$("div").remove(".bigimg");//clear big snap shot image
				self.reloadBroadcast();
			}
		},19*1000);
	};
	
	//Reload broadcast grid data from server
	this.reloadBroadcast=function(){	
		broadcastGrid.clearAll();
		broadcastGrid.load("<c:url value='/app/manage/conf/control/broadcast'/>?number="+selectedConfNumber,self.load_broadcastcallback, "json");
	};

    this.load_broadcastcallback=function(){
		//$(cellContent.view(V_CONF_CONTROL)).find("span[title^='$']").each(function(){
        $(cellContent).find("span[title^='$']").each(function(){
			parseElementTitle(this);
		});
	};
	this.fetchConfStatusOk=function(){
        //load participant grid data with json object
		if(confStatus.participants){
			//load participants（将confStatus.participants数据填充到表格中）
			confCtrlPtcGrid.parse(confStatus.participants,function(){
				//$(cellContent.view(V_CONF_CONTROL)).find("img[title^='$'],span[title^='$']").each(function(){
                $(cellContent).find("img[title^='$'],span[title^='$']").each(function(){
					parseElementTitle(this);
				});

				//$(cellContent.view(V_CONF_CONTROL)).find(".i18n").each(function(){
                $(cellContent).find(".i18n").each(function(){
					$(this).text(messages.getMsg($(this).text().replace("$","")));
				});
			},"json");
		}

		self.configSnapShot();
        //cellContent.progressOff();
    }
    this.fetchConfStatusFail=function(){
         //cellContent.progressOff();
    }
	this.fetchConfStatus=function(){		
		$.ajax({
			url:"<c:url value='/app/manage/conf/status/json'/>",
			//async:false,
			type:"GET",
			data:{
				times:new Date().valueOf(),
				number:selectedConfNumber
			},
            error: function (request, status, error) {
                self.fetchConfStatusFail();
                //alert(request.responseText);
            },
			success:function(data){
				confStatus=$.parseJSON(data);
                self.fetchConfStatusOk();
			}
		});
	};
	
	this.showLayoutStyle = function(styleIndex){
		$.each([1,2,3,4,5,6,7,8,9,10,13,16],function(){
			if(this!=styleIndex){
				$("#layout_"+this).css("display","none");
				//$("#layout_"+this).find("select").css("display","none");
			}else{
				$("#layout_"+this).css("display","block");
				//$("#layout_"+this).find("select").css("display","block");
			}
		});
	};
	
	//configurate conference snap shot image representation
	this.configSnapShot=function(){
		var x = 10;
		var y = 20;
		$("div[tab_id=id_tab_participant]").find("img[src*='/snapshot/']").attr("src",function(){
			return "${sessionScope.loginInfo.managerURL}"+this.src.substring(this.src.indexOf("/snapshot/"),this.src.length)+"?times="+new Date().valueOf();
		}).mouseover(function(e){
			var _src=this.src;
			
			if(_src.indexOf("notfound.gif")!=-1) return;
			
			//var imgId=_src.substring(_src.lastIndexOf("/")+1,_src.lastIndexOf("?")).replace(".jpg","");
			var imgId=$(this).attr("imgid");
			var imgDivId="__img_"+imgId;
			if($("#"+imgDivId).size()==0){
				$("<div id='"+imgDivId+"' class='bigimg'><img src='/snapshot/"+imgId+"_big.jpg' width='240' height='180'/></div>").appendTo("body").css({
					"position":"absolute",
					"z-index":10,
					"border-style":"ridge",
					"border-color":"gray",
					"border-width":"thin"
				}).hide();
			}
			
			var _left=$(this).offset().left;
			var _top=$(this).offset().top;			
			
			$("#"+imgDivId).find("img").attr("src",function(){
				return "${sessionScope.loginInfo.managerURL}"+this.src.substring(this.src.indexOf("/snapshot/"),this.src.length)+"?times="+new Date().valueOf();
			});
			
			$("#"+imgDivId).css({
				"left":_left-250,
				"top":_top-80			
			}).show("slow");
		}).mouseout(function(){
			var _src=this.src;			
			if(_src.indexOf("notfound.gif")!=-1) return;			
			//var imgId=_src.substring(_src.lastIndexOf("/")+1,_src.lastIndexOf("?")).replace(".jpg","");
			var imgId=$(this).attr("imgid");			
			var imgDivId="__img_"+imgId;			
			$("#"+imgDivId).hide();
		});
	};
    this.initDebugInfo=function() {
        $("#id_members").text(confStatus.members);
		$("#id_speaker").text(confStatus.speaker);
		$("#id_pollers").text(confStatus.pollers);
		$("#id_audiomixers").text(confStatus.audiomixers);
		$("#id_speakers").text(confStatus.speakers);
		$("#id_screens").text(confStatus.screens);
		$("#id_encoders").text(confStatus.encoders);
     }
    this.initSendMsg=function() {
        $("input[name=message]").val(confStatus.message);
		$("input[name=msgDisplayTime]").val(confStatus.msgTimeout);
		$("input[name=msgDisplayPos][value="+confStatus.msgPos+"]").attr("checked",true);
		$("input[name=msgFontSize][value="+confStatus.msgFontSize+"]").attr("checked",true);
		$("#id_msgColor").val(confStatus.msgColor).css("background-color",confStatus.msgColor||"#ffffff");
		$("#id_msgBgColor").val(confStatus.msgBgColor).css("background-color",confStatus.msgBgColor||"#ffffff");
    }
    this.initConfInfo=function() {
        $("#id_confNumber").text(confStatus.number);
		$("#id_confName").text(confStatus.name);
		$("#id_beginTime").text(confStatus.startTime);
		$("#id_audioPorts").text(confStatus.audioPorts);
		$("#id_videoPorts").text(confStatus.videoPorts);
		$("#id_h239").text(confStatus.h239Start=="true"?"<fmt:message key='form.common.enable'/>":"<fmt:message key='form.common.h239notstart'/>");
    }
    this.reloadLayout=function(){
        if(!confStatus) {
			return ;
		}
        $("input[name=pollTime]").val(confStatus.pollTime||"");
		var layout=confStatus.layoutStyle||"";
		this.showLayoutStyle(layout);
		//clear checked
		$("input[name=layoutStyle]").attr("checked",false);
		//checked by layout value
		$("input[name=layoutStyle][value="+layout+"]").attr("checked",true);
        
		var $select=$("#id_layout").find("select[order]");

        //$select.children().remove(); //删除节点
        $select.each(function(){
            //被注释下面代码在IE8下不能正确运行
            //var $opt1 = $("<option value='' callid=''  stype='auto'><fmt:message key='custom.layout.auto'/></option>");
            //var $opt2 = $("<option value='' callid='' stype='poll'><fmt:message key='custom.layout.poll'/></option>");
            //var $opt3 = $("<option value='' callid='' stype='speaker'><fmt:message key='custom.layout.speaker'/></option>");
            //this.options[this.length]="<option value='' callid=''  stype='auto'><fmt:message key='custom.layout.auto'/></option>";
            //this.options[this.length]=$opt2.get(0);
            //this.options[this.length]=$opt3.get(0);
            
            $(this).children().remove();

            var op1=new Option("<fmt:message key='custom.layout.auto'/>","");
			$(op1).attr("callid","").attr("stype","auto");
			this.options[this.length]=op1;
            var op2=new Option("<fmt:message key='custom.layout.poll'/>","");
			$(op2).attr("callid","").attr("stype","poll");
			this.options[this.length]=op2;
            var op3=new Option("<fmt:message key='custom.layout.speaker'/>","");
			$(op3).attr("callid","").attr("stype","speaker");
			this.options[this.length]=op3;
        });

		$select.find("option[stype=auto]").attr("selected",true);
        // 将与会人员放入下拉列表中
		if(confStatus.participants&&confStatus.participants.rows.length>0){
			//Rows data format rows:[{id:xxx,data:[]},{}]
			var rows=confStatus.participants.rows;
			//$select.children().remove("option[stype='participant']");
			var opts=[];
			$.each(rows,function(){
                // 只有在线的人员才能进行分屏设置
                if(this.data[9] != "false")
				opts.push({txt:this.data[2],callid:this.id});
			});

			$select.each(function(){
				var j;
				for(j=0;j<opts.length;j++){
					//if($(this).find("option[stype='participant'][callid='"+opts[j].callid+"']").length==0)
                    {
						var op=new Option(opts[j].txt,"");
						$(op).attr("callid",opts[j].callid).attr("stype","participant");
						this.options[this.length]=op;
					}
				}
			});
		}

		setTimeout(function(){
			var panes=confStatus.panes;
			var $layout=$("#layout_"+layout);
			$.each(panes,function(){
				var order=parseInt(this.pos)+1;
				var type=this.type;
				var callId=this.callId;
				if(type=="participant"){
					$layout.find("select[order='"+order+"']").children("option[stype='participant'][callid='"+callId+"']").attr("selected",true);
				}else{
					$layout.find("select[order='"+order+"']").children("option[stype='"+type+"']").attr("selected",true);
				}
			});
		},100);
    }

	this.reloadValues=function(){
		//cellContent.progressOn();
        confCtrlPtcGrid.clearAll();
		confCtrlPtcToolbar.setItemImage("id_btn_checkall", "<c:url value='/styles/default/images/chk_no.gif'/>");
		confCtrlPtcToolbar.setItemState("id_btn_checkall", false);
		
		self.fetchConfStatus();
		
		// ------------ initialize custom layout tab values----------------
        firstTimeInitLayout = true;
		
		//-------------- initialize conference information tab values-----------------
        firstTimeInitConfInfo = true;

		//-------------- initialize send message tab values --------------------------
        firstTimeInitSendMsg = true;

		// ------------ initialize debug ---------------
		firstTimeInitDebugInfo = true;

		//this.reloadBroadcast();
        firstTimeInitBroadcastInfo = true;

	};
	
	this.initParticipantsTab=function(){        
		
		//Do hang up calls
		function hangUpCalls(calls){
			if(!calls) return;
			
			$.ajax({
				url:"<c:url value='/app/manage/conf/control/hangup'/>",
				type:"POST",
				async:false,
				data:{
					times:new Date().valueOf(),
					_method:"PUT",
					number:selectedConfNumber,
					calls:calls
				},
				success:function(data){
					//alert(data);
					self.reloadValues();
				}
			});
		}
		// 邀请与会者
		function inviteParticipants(calls){
			if(!calls) return;

			$.ajax({
				url:"<c:url value='/app/manage/conf/control/invite'/>",
				type:"POST",
				async:false,
				data:{
					times:new Date().valueOf(),
					_method:"PUT",
					number:selectedConfNumber,
					calls:calls
				},
				success:function(data){
					//alert(data);
					self.reloadValues();
				}
			});
		}
		
		//Mute or cancel mute calls
		function muteCalls(calls,isMute){
			if(!calls) return;
			
			$.ajax({
				url:"<c:url value='/app/manage/conf/control/mute'/>",
				type:"POST",
				async:false,
				data:{
					times:new Date().valueOf(),
					_method:"PUT",
					number:selectedConfNumber,
					calls:calls,
					mute:isMute
				},
				success:function(data){
					//alert(data);
					self.reloadValues();
				}
			});
		}
		
		// Specify or cancel conference lecture
		function specifyLecture(cancel,callId){
			$.ajax({
				url:"<c:url value='/app/manage/conf/control/lecture'/>",
				type:"POST",
				async:false,
				data:{
					times:new Date().valueOf(),
					_method:"PUT",
					number:selectedConfNumber,
					callId:callId||"",
					cancel:cancel
				},
				success:function(data){
					//alert(data);
					self.reloadValues();
				}
			});
		}
		
		//End conference
		function endConf(){
			$.ajax({
				url:"<c:url value='/app/manage/conf/control/endConf'/>",
				type:"POST",
				async:false,
				data:{
					times:new Date().valueOf(),
					_method:"PUT",
					number:selectedConfNumber
				},
				success:function(data){
					//alert(data);
					onlineConfObj.reload();
					
					cellContent.hideHeader();
					cellContent.view("def").setActive();
				}
			});
		}
		
		/**
		 * Drag participant to conference from address book  
		 * @param sGrid grid of address book 
		 */
		function dargToConfFromAddressBook(sGrid){
			var ptcs=[];
			var rowIds=sGrid.getSelectedRowId();
			if(rowIds==null) return;
			
			$.each(rowIds.split(","),function(){
				ptcs.push({
					"p_number":sGrid.cells(this,0).getValue(),
					"p_ip":sGrid.cells(this,5).getValue(),
					"p_videoEnabled":"true",
					"p_bandwidth":sGrid.cells(this,4).getValue()
				});	
			});
			
			$.ajax({
				url:"<c:url value='/app/manage/conf/control/invite'/>",
				type:"POST",
				data:{
					times:new Date().valueOf(),
					number:selectedConfNumber,
					participants:$.toJSON(ptcs)
				},
				success:function(data){
					//alert(data);
					self.reloadValues();
				}
			});
		}
		
		confCtrlPtcToolbar=confCtrlTabbar.cells("id_tab_participant").attachToolbar();
		var i=1;
		confCtrlPtcToolbar.addButtonTwoState("id_btn_checkall", i++, "<fmt:message key='btn.checkall'/>","<c:url value='/styles/default/images/chk_no.gif'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_hangup",i++,"","<c:url value='/styles/default/images/link_break.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_link",i++,"","<c:url value='/styles/default/images/link.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_invite",i++,"","<c:url value='/styles/default/images/contact16.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_addfrombook",i++,"","<c:url value='/styles/default/images/addressbook16.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_mute",i++,"","<c:url value='/styles/default/images/unmute.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_cancel_mute",i++,"","<c:url value='/styles/default/images/mute.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_lecture",i++,"","<c:url value='/styles/default/images/lecture_set.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_lecture_cancel",i++,"","<c:url value='/styles/default/images/lecture_cancel.png'/>");	
		confCtrlPtcToolbar.addButton("id_p_btn_stop",i++,"","<c:url value='/styles/default/images/close16.png'/>");
		confCtrlPtcToolbar.addButton("id_p_btn_info",i++,"","<c:url value='/styles/default/images/info-16.png'/>");
		
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_hangup","<fmt:message key='toolbar.confControl.hangup'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_link","<fmt:message key='toolbar.confControl.link'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_info","<fmt:message key='toolbar.confControl.info'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_mute","<fmt:message key='toolbar.confControl.mute'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_cancel_mute","<fmt:message key='toolbar.confControl.cancelMute'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_lecture","<fmt:message key='toolbar.confControl.lecture'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_lecture_cancel","<fmt:message key='toolbar.confControl.cancelLecture'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_invite","<fmt:message key='toolbar.confControl.invite'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_addfrombook","<fmt:message key='toolbar.confControl.addfrombook'/>");
		confCtrlPtcToolbar.setItemToolTip("id_p_btn_stop","<fmt:message key='toolbar.confControl.end'/>");
		
		confCtrlPtcToolbar.attachEvent("onClick",function(id){
			var calls=confCtrlPtcGrid.getSelectedRowId();
			if(id=="id_p_btn_hangup"){
				if(calls!=null){
					//if(confirm(messages.getMsg("confirm.hangup")))
					{
						hangUpCalls(calls);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}
			if(id=="id_p_btn_link"){
				if(calls!=null){
					//if(confirm(messages.getMsg("confirm.mute")))
					{
						inviteParticipants(calls);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}
			if(id=="id_p_btn_mute"){
				if(calls!=null){
					//if(confirm(messages.getMsg("confirm.mute")))
					{
						muteCalls(calls,"true");
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}
			if(id=="id_p_btn_cancel_mute"){
				if(calls!=null){
					//if(confirm(messages.getMsg("confirm.cancelMute")))
					{
						muteCalls(calls,"false");
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}
			if(id=="id_p_btn_lecture"){
				if(calls!=null){
					if(calls.indexOf(",")!=-1){
						//alert(messages.getMsg("oneSelect.tip"));
					}else //if(confirm(messages.getMsg("confirm.setLecture")))
					{
						specifyLecture("false",calls);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}
			if(id=="id_p_btn_lecture_cancel"){
				//if(confirm(messages.getMsg("confirm.cancelLecture")))
				{
					specifyLecture("true");
				}
			}
			if(id=="id_p_btn_stop"){
				if(confirm(messages.getMsg("confirm.endConf"))){
					endConf();
				}
			}
			if(id=="id_p_btn_info"){
				if(calls!=null){
					if(calls.indexOf(",")!=-1){
						//alert(messages.getMsg("oneSelect.tip"));
					}else{
						var url="<c:url value='/app/manage/conf/control/callDetail'/>?number="+selectedConfNumber+"&callId="+calls;
						openWin("<fmt:message key='pop.title.detail'/>",url,520,540);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
			}
			if(id=="id_p_btn_invite"){
				var url1="<c:url value='/app/manage/conf/control/invite/enter'/>?number="+selectedConfNumber;
				openWin("<fmt:message key='pop.title.invite'/>",url1,300,200);
			}
			if(id=="id_p_btn_addfrombook"){
				var url2="<c:url value='/app/manage/addressbook/win'/>?parent=main";
				openWin("<fmt:message key='panel.title.addressBook'/>",url2,600,480);
			}
		});
		
		confCtrlPtcToolbar.attachEvent("onStateChange",function(id,state){
			if(id=="id_btn_checkall"){
				if(state){
					confCtrlPtcToolbar.setItemImage("id_btn_checkall", "<c:url value='/styles/default/images/chk_yes.gif'/>");
					confCtrlPtcGrid.selectAll();
				}else{
					confCtrlPtcToolbar.setItemImage("id_btn_checkall", "<c:url value='/styles/default/images/chk_no.gif'/>");
					confCtrlPtcGrid.clearSelection();
				}
			}
		});

		confCtrlPtcGrid=confCtrlTabbar.cells("id_tab_participant").attachGrid();
		confCtrlPtcGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		confCtrlPtcGrid.setHeader([
						"",
						"<fmt:message key='grid.confControl.header.number'/>",
						"<fmt:message key='grid.confControl.header.name'/>",
						"<fmt:message key='grid.confControl.header.status'/>",
						"<fmt:message key='grid.confControl.header.mute'/>",
						"<fmt:message key='grid.confControl.header.micmute'/>",
						"<fmt:message key='grid.confControl.header.bandwidth'/>",
						"<fmt:message key='grid.confControl.header.direction'/>",
						"<fmt:message key='grid.confControl.header.preview'/>"
		                ],null,[
								"text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
		                        "text-align:center",
								"text-align:center",
		                        "text-align:center"]);
		confCtrlPtcGrid.setInitWidths("26,106,90,70,54,54,70,60,*");
		confCtrlPtcGrid.setSkin("${skin}");
		confCtrlPtcGrid.enableMultiselect(true);
		confCtrlPtcGrid.setColSorting("str,str,str,na,na,na,str,na,na");
		confCtrlPtcGrid.enableTooltips("false,fales,fales,fales,fales,fales,fales,false,false");
		confCtrlPtcGrid.setColAlign("center,left,left,center,left,left,center,center,left");
		confCtrlPtcGrid.setStyle("","","","font-weight:bold;background-color:#FFF1CC;background-image:url(aababafsd.png);");
		// background-image:url(aababafsd.png); 用来防止选中时显示不正确

		confCtrlPtcGrid.enableDragAndDrop(true);
		//Make this grid do not support drag out
		confCtrlPtcGrid.attachEvent("onBeforeDrag", function(id){
	    	return false;
	    });
		confCtrlPtcGrid.attachEvent("onDrag", function(sId,tId,sObj,tObj,sInd,tInd){
			dargToConfFromAddressBook(sObj);
	    	return false;
	    });
		
		confCtrlPtcGrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro,ro");
		confCtrlPtcGrid.attachEvent("onRowDblClicked", function(rid,cindex){
			var url="<c:url value='/app/manage/conf/control/callDetail'/>?number="+selectedConfNumber+"&callId="+rid;
			openWin("<fmt:message key='pop.title.detail'/>",url,520,540);
		});
		confCtrlPtcGrid.init();
	};
	
	this.initLayoutTab=function(){
		confCtrlTabbar.setContentHTML("id_tab_layout","<div id='id_layout_temp'></div>");
		$("#id_layout_temp").replaceWith($("#id_layout"));
		$("#id_layout").css("display","block");
		$("input[name=layoutStyle]").click(function(){
			self.showLayoutStyle(this.value);
		});
	};
	
	this.initInfoTab=function(){
		confCtrlTabbar.setContentHTML("id_tab_confInfo","<div id='id_info_temp'></div>");
		$("#id_info_temp").replaceWith($("#id_info"));
		$("#id_info").css("display","block");
	};
	
	this.initSendMessageTab=function(){
		confCtrlTabbar.setContentHTML("id_tab_sendMsg","<div id='id_sendMsg_temp'></div>");
		$("#id_sendMsg_temp").replaceWith($("#id_sendMsg"));
		$("#id_sendMsg").css("display","block");
		
		//initialize color picker
		//var cp1 = new dhtmlXColorPickerInput('id_msgColor');
		var cp1 = new dhtmlXColorPicker("cp_txt",false,false,true);
		cp1.loadUserLanguage("my-lang");
		cp1.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		cp1.init();
		cp1.setOnSelectHandler(function(c){
			$("#id_msgColor").val(c);
			$("#id_msgColor").css("background-color",c);
		});
		$("#id_msgColor").click(function(e){
			cp1.setPosition(e.pageX,e.pageY);
			cp1.show();
		});
		var cp2 = new dhtmlXColorPicker("cp_bg",false,false,true);
		cp2.loadUserLanguage("my-lang");
		cp2.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		cp2.init();
		cp2.setOnSelectHandler(function(c){
			$("#id_msgBgColor").val(c);
			$("#id_msgBgColor").css("background-color",c);
		});
		$("#id_msgBgColor").click(function(e){
			cp2.setPosition(e.pageX,e.pageY);
			cp2.show();
		});
	};
	
	this.initDebugTab=function(){
		confCtrlTabbar.setContentHTML("id_tab_debug","<div id='id_debug_temp'></div>");
		$("#id_debug_temp").replaceWith($("#id_debug"));
		$("#id_debug").css("display","block");
	};
	
	this.initBroadcastTab=function(){
		broadcastGrid=confCtrlTabbar.cells("id_tab_broadcast").attachGrid();
		broadcastGrid.setHeader([
		       					"<fmt:message key='grid.broadcast.header.dialogId'/>",
                                "<fmt:message key='grid.broadcast.header.status'/>",
		       					"<fmt:message key='grid.broadcast.header.address'/>",
		       					"<fmt:message key='grid.broadcast.header.duration'/>"
		       	                ],null,[
		       	                        "text-align:center",
                                        "text-align:center",
		       	                        "text-align:center",
		       	                        "text-align:center"]);
		broadcastGrid.setInitWidths("180,70,120,*");
		broadcastGrid.setSkin("${skin}");
		broadcastGrid.setColTypes("ro,ro,ro,ro");
        broadcastGrid.enableTooltips("fales,fales,fales,fales");
		broadcastGrid.init();
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		confCtrlTabbar.setTabActive("id_tab_participant");
		
		// 在“会议控制”的标题上也加上会议号的显示
		activeCellContent("<fmt:message key='cellContent.title.confControl'/>"+"("+selectedConfNumber+")", V_CONF_CONTROL, function(){
			self.reloadValues();
		});
		
		setRefresh(cellContent, function(){
			self.reloadValues();
			confCtrlTabbar.setTabActive("id_tab_participant");
		});
	};
	
	// do save layout
	this.saveLayout=function(){
		var _panesJSON="";
		var _layoutStyle=$("input[name='layoutStyle']").filter(function(){return this.checked;}).val();
		
		if(_layoutStyle){
			var _panes=[];
			$("#layout_"+_layoutStyle).find("select").each(function(){
				var _pos=parseInt($(this).attr("order"))-1;
				var _type=$(this.options[this.selectedIndex]).attr("stype");
				var _callId=$(this.options[this.selectedIndex]).attr("callid");
				
				_panes.push({
					pos:_pos,
					type:_type,
					callId:_callId
				});
			});
			
			_panesJSON=$.toJSON(_panes);
			
			$.ajax({
				url:"<c:url value='/app/manage/conf/control/layout'/>",
				type:"POST",
				async:false,
				data:{
					_method:"PUT",
					times:new Date().valueOf(),
					number:selectedConfNumber,
					pollTime:$("input[name=pollTime]").val(),
					layoutStyle:_layoutStyle,
					panesJSON:_panesJSON
				},
				success:function(data){
					//alert(data);
					self.reloadValues();
					self.activeLayoutTabForIE();
				}
			});
		}
	};
	
	// 这个方法没用了
	this.activeLayoutTabForIE=function(){
		if($.browser.msie){
			//confCtrlTabbar.setTabActive("id_tab_debug");
			//confCtrlTabbar.setTabActive("id_tab_layout");
		}
	};
	
	// do auto layout
	this.autoLayout=function(){
		$.ajax({
			url:"<c:url value='/app/manage/conf/control/layout/auto'/>",
			type:"POST",
			async:false,
			data:{
				times:new Date().valueOf(),
				_method:"PUT",
				number:selectedConfNumber
			},
			success:function(data){
				//alert(data);
				self.reloadValues();
				self.activeLayoutTabForIE();
				
				self.showLayoutStyle(-1);
				$("input[name=layoutStyle]").attr("checked",false);
			}
		});
	};
	
	//do send message
	this.sendMessage=function(){
		$.ajax({
			url:"<c:url value='/app/manage/conf/control/sendMessage'/>",
			type:"POST",
			async:false,
			data:{
				times:new Date().valueOf(),
				_method:"PUT",
				number:selectedConfNumber,
				message:$("input[name=message]").val(),
				msgDisplayTime:$("input[name=msgDisplayTime]").val(),
				msgDisplayPos:$("input[name=msgDisplayPos]").filter(function(){return this.checked;}).val(),
				msgFontSize:$("input[name=msgFontSize]").filter(function(){return this.checked;}).val(),
				msgColor:$("input[name=msgColor]").val(),
				msgBgColor:$("input[name=msgBgColor]").val()
			},
			success:function(data){
				//alert(data);
				self.reloadValues();
			}
		});
	};
}

// -------------------CDR----------------------
function CDRView(){
	var cdrGrid,V_CDR="v_cdr";
	var self=this;
	var pageId="page_"+(new Date().valueOf());
	var $page=$(document.createElement("div"));
    var $pageQuery=$(document.createElement("div"));
    var $pageUser=$(document.createElement("div"));
	var $pageCtn=null;
	var PAGE_LIMIT_NUM=20;
	var pageNum=0,pagelimit=PAGE_LIMIT_NUM,totalPageNum=0,start=0,inited=false;
    var start_date=null;
    var end_date=null;
    var caller=null, called=null;
    var browse=true;
    var billtime_pos;
    var toolbar;


    this.initDate=function(){
       var edate = new Date();

        // 计算上个月是多少天
        var n;
        var daysInMonth = new Array([31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]);
        if(edate.getFullYear()%100==0 && edate.getFullYear()%400==0)
            daysInMonth[1]=29; //闰年
        else if (edate.getFullYear()%4==0 && edate.getFullYear()%100!=0)
            daysInMonth[1]=29; //闰年
        if(edate.getMonth()>0)
            n = daysInMonth[edate.getMonth()];
        else
            n = 31;
        var sdate = new Date(edate-n*86400000); //上个月同一天
        end_date = edate.getFullYear()+"-"+(edate.getMonth()+1)+"-"+edate.getDate();
        start_date = sdate.getFullYear()+"-"+(sdate.getMonth()+1)+"-"+sdate.getDate();
         // 将2005-8-5转换成2005-08-05格式
        end_date  = end_date.replace(/\b(\w)\b/g, '0$1');
        start_date  = start_date.replace(/\b(\w)\b/g, '0$1');
   }
	
	this.clearPageValues=function(){
		pageNum=0;
		pagelimit=PAGE_LIMIT_NUM;
		totalPageNum=0;
		start=0;
	};
	
	this.init=function(){
        this.initDate();
		this.buildPagination();
		
		toolbar=cellContent.view(V_CDR).attachToolbar();
		var ti=0;

		toolbar.addText("id_btn_download_cdr",ti++,'<a href="${sessionScope.loginInfo.managerURL}/cdr/cdr.txt?times='+new Date().valueOf()+'" target="_blank"><fmt:message key="btn.download"/></a>');
		toolbar.addText("id_text_page_cdr",ti++,'<div id="'+pageId+'">'+$page.html()+'</div>');
        toolbar.addText("id_text_date_cdr",ti++,$pageQuery.html());
        toolbar.addText("id_text_user_cdr",ti++,$pageUser.html()); 
        toolbar.addButton("id_btn_query_cdr",ti++,"","<c:url value='/styles/default/images/search.png'/>");
        billtime_pos = ti;
        toolbar.setItemToolTip("id_btn_query_cdr","<fmt:message key='view.cdr.search'/>");

        toolbar.attachEvent("onClick", function(id){
            if(id == "id_btn_query_cdr"){
                self.clearPageValues();
                browse = false;
                //start_date =  $('#id_input_start_date_cdr').val();
                //end_date =  $('#id_input_end_date_cdr').val();
                //caller =  $('#id_input_caller_cdr').val();
                //called =  $('#id_input_called_cdr').val();
                if(DateDiff(end_date,start_date)>31) {
                    alert("<fmt:message key='view.cdr.datelimit'/>");
                    return;
                }
                self.reload();
            }
        });
     
		$pageCtn=$("#"+pageId);
		$pageCtn.find(".cls_prev").click(this.prev);
		$pageCtn.find(".cls_next").click(this.next);
		
		cdrGrid=cellContent.view(V_CDR).attachGrid();
		cdrGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		cdrGrid.setHeader([
							"<fmt:message key='grid.view.cdr.time'/>",
							"<fmt:message key='grid.view.cdr.address'/>",                            
							"<fmt:message key='grid.view.cdr.caller'/>",
							"<fmt:message key='grid.view.cdr.called'/>",
							"<fmt:message key='grid.view.cdr.duration'/>",
							"<fmt:message key='grid.view.cdr.status'/>",
							"<fmt:message key='grid.view.cdr.direction'/>",
							"<fmt:message key='grid.view.cdr.reason'/>",
                            "<fmt:message key='grid.view.cdr.application'/>"
			                ],null,[
			                        "text-align:center",                                    
                                    "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center",
			                        "text-align:center"
			                     ]);
		cdrGrid.setInitWidths("110,110,100,100,80,75,75,130,180");
		//cdrGrid.setColSorting("date");
		cdrGrid.setColAlign("left,left,left,left,right,left,left,left,left");
		cdrGrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro,ro");
		cdrGrid.enableTooltips("fales,fales,fales,fales,fales,fales,fales,fales,fales");
		cdrGrid.setStyle("","","","font-weight:bold;");
		cdrGrid.setSkin("${skin}");
		cdrGrid.init();
		
		inited=true;
	};
	
	this.buildPagination=function(){
		$page.append('<div style="float:left;padding:0px 3px;"><fmt:message key="page.total"/>:</div>');
		$page.append('<div style="float:left;padding:0px 3px;" class="cls_total"></div>');
        $page.append('<div style="float:left;padding:0px 3px;">&nbsp</div>');
		$page.append('<div style="float:left;padding:0px 3px;"><fmt:message key="page.page"/>:</div>');
		$page.append('<div style="float:left;padding:0px 3px;" class="cls_page_cnt"></div>');
		$page.append('<div style="float:left;padding:0px 3px;">/</div>');
		$page.append('<div style="float:left;padding:0px 3px;" class="cls_page_all"></div>');
		$page.append('<div style="float:left;padding:0px 10px;" class="cls_nav"><a href="#" class="cls_prev"><fmt:message key="page.prev"/></a>&nbsp;&nbsp;&nbsp<a href="#" class="cls_next"><fmt:message key="page.next"/></a></div>');      
        //$page.append('<div style="clear:both;" />');

        $pageQuery.append('<div style="float:left;"><input id="id_input_start_date_cdr" style="width:80px;height:14px;" title="<fmt:message key="grid.view.cdr.time" />" type="text" name="start_date"></div>');
        $pageQuery.append('<div style="float:left;">&nbsp;-&nbsp;</div>');
        $pageQuery.append('<div style="float:left;"><input id="id_input_end_date_cdr" style="width:80px;height:14px;" title="<fmt:message key="grid.view.cdr.time" />" type="text" name="end_date"></div>');

        $pageUser.append('<div style="float:left;"><fmt:message key="view.cdr.caller"/></div>');
        $pageUser.append('<div style="float:left;"><input style="width:80px;height:14px;" id="id_input_caller_cdr" type="text" value="" name="caller"></div>');
        $pageUser.append('<div style="float:left;"><fmt:message key="view.cdr.called"/></div>');
        $pageUser.append('<div style="float:left;"><input style="width:80px;height:14px;" id="id_input_called_cdr" type="text" value="" name="called"></div>');
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		activeCellContent("<fmt:message key='view.cdr.title'/>",V_CDR,function(){
            browse = false;
			self.clearPageValues();
			self.reload();
		});
		
		setRefresh(cellContent, function(){
            browse = false;
			self.clearPageValues();
			self.reload();
		});

        var myCalendar = new dhtmlXCalendarObject(["id_input_start_date_cdr","id_input_end_date_cdr"]);
        myCalendar.hideTime();
    };
	
	this.reload=function(){
		cdrGrid.clearAll();
		var pageResult=this.queryCDR();
		var total=pageResult.total;
        
		/*
        if(!browse){
            toolbar.removeItem("id_text_billtime");
            var billtime= '<fmt:message key="view.cdr.billtime"/>' + ": "+pageResult.billtime;
            toolbar.addText("id_text_billtime", billtime_pos, billtime);
        }
        else
            toolbar.removeItem("id_text_billtime");
        */
		
        this.setPaginationValues(total);
		cdrGrid.parse(pageResult.result,"json");
		//cdrGrid.sortRows(0,"date","des");
		//cdrGrid.setSortImgState(true,0,"des");
	};
	
	this.queryCDR=function(){
		var ret=null;
		
		start_date =  $('#id_input_start_date_cdr').val();
        end_date =  $('#id_input_end_date_cdr').val();
        caller =  $('#id_input_caller_cdr').val();
        called =  $('#id_input_called_cdr').val();
        
		$.ajax({
			url:"<c:url value='/app/view/cdr'/>",
			type:"GET",
			async:false,
			data:{
				times:new Date().valueOf(),
				start:start,
				pagelimit:pagelimit,
                browse:browse,
                start_date:start_date,
                end_date:end_date,
                caller:caller||"",
                called:called||""
			},
			success:function(data){
				ret=$.parseJSON(data);
			}
		});
		
		return ret;
	};
	
	this.setPaginationValues=function(total){
		var _total=parseInt(total);
		$pageCtn.find(".cls_total").text(_total);
		if(_total>0){
			totalPageNum=_total%pagelimit==0?_total/pagelimit:(parseInt(_total/pagelimit)+1);
			$pageCtn.find(".cls_page_cnt").text(pageNum==0?++pageNum:pageNum);
			$pageCtn.find(".cls_page_all").text(totalPageNum);
		}else{
			$pageCtn.find(".cls_page_cnt").text(0);
			$pageCtn.find(".cls_page_all").text(0);
		}
	};

	
	this.prev=function(){
        //browse = true;
		if(pageNum>1){
			pageNum--;
			start-=pagelimit;
			self.reload();
		}
	};
	
	this.next=function(){
       // browse = true;
		if(pageNum<totalPageNum){
			pageNum++;
			start+=pagelimit;
			self.reload();
		}
	};
}

// -------------------History----------------------
function HistoryView(){
	var V_HISTORY="v_history";
	var self=this;
    var start_date=null;
    var end_date=null;
    var inited=false;
    var $page=$(document.createElement("div"));
    var chart;
    /*
    var chart_data = [
        {mvideo:"3", date:"1982-10-1"},
		{mvideo:"6", date:"1983"},
        ...
	];
    */
   this.initDate=function(){
       var edate = new Date();

        // 计算上个月是多少天
        var n;
        var daysInMonth = new Array([31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]);
        if(edate.getFullYear()%100==0 && edate.getFullYear()%400==0)
            daysInMonth[1]=29; //闰年
        else if (edate.getFullYear()%4==0 && edate.getFullYear()%100!=0)
            daysInMonth[1]=29; //闰年
        if(edate.getMonth()>0)
            n = daysInMonth[edate.getMonth()];
        else
            n = 31;
        var sdate = new Date(edate-n*86400000); //上个月同一天
        end_date = edate.getFullYear()+"-"+(edate.getMonth()+1)+"-"+edate.getDate();
        start_date = sdate.getFullYear()+"-"+(sdate.getMonth()+1)+"-"+sdate.getDate();
         // 将2005-8-5转换成2005-08-05格式
        end_date  = end_date.replace(/\b(\w)\b/g, '0$1');
        start_date  = start_date.replace(/\b(\w)\b/g, '0$1');
   }

	this.buildPage=function(){      
        $page.append('<div style="float:left;padding:0px 3px;"><fmt:message key="view.history.start_date"/></div>');
        $page.append('<div style="float:left;padding:0px 3px; "><input id="id_input_start_date" style="height:14px;" type="text" value="'+start_date+'" name="start_date"></div>');
        $page.append('<div style="float:left;padding:0px 3px;"><fmt:message key="view.history.end_date"/></div>');
        $page.append('<div style="float:left;padding:0px 3px;"><input id="id_input_end_date" style="height:14px;" type="text" value="'+end_date +'" name="end_date"></div>');
	};

	this.init=function(){
        self.initDate();
        self.buildPage();
        var toolbar=cellContent.view(V_HISTORY).attachToolbar();
        
        inited=true;
        var ti=0;
        toolbar.addText("id_h_text_page",ti++,'<div id="id_histroy_page_div">'+$page.html()+'</div>');
        toolbar.addButton("id_h_btn_query",ti++,"","<c:url value='/styles/default/images/search.png'/>");
        toolbar.setItemToolTip("id_h_btn_query","<fmt:message key='view.history.search'/>");
        
        toolbar.attachEvent("onClick", function(id){
            if(id == "id_h_btn_query"){
                start_date =  $('#id_input_start_date').val();
                end_date =  $('#id_input_end_date').val();               
                self.queryHistory(start_date,end_date);                
            }
        });
       
        var chartConfig =  {
            view:"line",
            //container:"chart_container",
            value:"#mvideo#",
            label:"#mvideo#",          
            item:{
                borderColor:"#ff9900",
                color:"#ffffff"
            },
            tooltip: {
                template: "#mvideo#"
            },
            line:{
                color:"#ff9900",
                width:3
            },
            xAxis:{
                template:"#date#"
            },
            yAxis:{
                end: '${sessionScope.loginInfo.maxPortNum}',
                start:0,
                step:2,
                title:'<fmt:message key="view.history.title"/>'
            },
            padding: {
                left: 35,
                bottom: 20
            },
            preset: "plot",
            origin: 0,
            legend: {
                layout: "x",
                width: 100,
                align: "center",
                valign: "top",
                marker: {
                    type: "round",
                    width: 15
                },
                values: [{
                        text: '<fmt:message key="view.history.video"/>',
                        color: "#ff9900"
                    }, {
                        text: '<fmt:message key="view.history.audio"/>',
                        color: "#3399ff"
                    }, {
                        text: '<fmt:message key="view.history.bcast"/>',
                        color: "#66cc00"
                    }]
            }
        };

        chart = cellContent.view(V_HISTORY).attachChart(chartConfig);

        chart.addSeries({
			value:"#maudio#",
            label:"#maudio#",
            item:{
                borderColor:"#3399ff",
                color:"#ffffff"
            },
            line:{
                color:"#3399ff",
                width:3
            },
            preset: "plot",
            tooltip: {
                template: "#maudio#"
            }
		});
		chart.addSeries({
			value:"#mbcast#",
            label:"#mbcast#",
            item:{
                borderColor:"#66cc00",
                color:"#ffffff"
            },
            line:{
                color:"#66cc00",
                width:3
            },
            preset: "plot",
            tooltip: {
                template: "#mbcast#"
            }
		});

    }

	this.active=function(){
		if(!inited) self.init();

		activeCellContent("<fmt:message key='view.history.title'/>",V_HISTORY,function(){
			self.reload();
		});

		setRefresh(cellContent, function(){
			self.reload();
		});

        var myCalendar = new dhtmlXCalendarObject(["id_input_start_date","id_input_end_date"]);
        myCalendar.hideTime();
	};

	this.reload=function(){
        self.initDate();
        self.queryHistory(start_date,end_date);
    };

	this.queryHistory=function(start_date, end_date){
		var ret=null;      
		$.ajax({
			url:"<c:url value='/app/view/history'/>",
			type:"GET",
			async:false,
			data:{
                'times':new Date().valueOf(),
				'start_date':start_date,
				'end_date':end_date
			},
			success:function(data){
                chart.clearAll();
				ret=$.parseJSON(data);                
                chart.parse(data,"json");
			}
		});
        return ret;
	};	
}
// ----------------- Network route ----------------
function NetworkRouteView(){
	var grid,V_NETWORK_ROUTE="v_network_route",self=this,inited=false;
	
	this.init=function(){
	    /*
		var toolbar=cellContent.view(V_NETWORK_ROUTE).attachToolbar();
		//var ti=0;
		
		toolbar.addButton("id_btn_add",ti++,"","<c:url value='/styles/default/images/table-add.png'/>");
		toolbar.addButton("id_btn_remove",ti++,"","<c:url value='/styles/default/images/table-delete.png'/>");
		// set tooltip
		toolbar.setItemToolTip("id_btn_add","<fmt:message key='btn.add'/>");
		toolbar.setItemToolTip("id_btn_remove","<fmt:message key='btn.remove'/>");
		
		toolbar.attachEvent("onClick",function(id){
			switch (id) {
			case "id_btn_add":
				openWin("<fmt:message key='pop.title.route.add'/>", "<c:url value='/app/setup/routes/route'/>", 300, 300,"table-add.png");
				break;
			case "id_btn_remove":
				var ids=grid.getSelectedRowId();
				
				if(ids!=null){
					//if(confirm(messages.getMsg("confirm.tip")))
					{
						self.removeRoutes(ids);
					}
				}else{
					//alert(messages.getMsg("noSelect.tip"));
				}
				break;
			}
		});
		*/
		
		grid=cellContent.view(V_NETWORK_ROUTE).attachGrid();
		grid.setSkin("${skin}");
		grid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		
		grid.setHeader([
						"<fmt:message key='setup.routes.destination'/>",
						"<fmt:message key='setup.routes.netmask'/>",
                        "<fmt:message key='setup.routes.gw'/>",
						"<fmt:message key='setup.routes.interface'/>",
                        "<fmt:message key='setup.routes.metric'/>"
		   		       ],null,[
  		                        "text-align:center",
  		                        "text-align:center",
                                "text-align:center",
                                "text-align:center",
  		                      	"text-align:center"
  		                      	]);
		grid.setInitWidths("140,140,140,180,100");
		grid.setColTypes("ro,ro,ro,ro,ro");
		grid.enableTooltips("fales,fales,fales,false,false");
		grid.setStyle("","","","font-weight:bold;");
		grid.init();
		
		inited=true;
	};
	
	this.removeRoutes=function(ids){
		var _routes=[];
		
		$.each(ids.split(","),function(){
			var obj={
				'net':grid.cells(this,0).getValue(),
				'netmask':grid.cells(this,1).getValue(),
				'iface':grid.cells(this,2).getValue()
			};
			
			_routes.push(obj);
		});
		
		$.ajax({
			url:"<c:url value='/app/setup/routes'/>",
			type:"POST",
			data:{
				'times':new Date().valueOf(),
				'routesJSON':$.toJSON(_routes),
				'_method':"DELETE"
			},
			success:function(data){
				//alert(data);
				self.reload();
			}
		});
	};
	
	this.reload=function(){
		cellContent.progressOn();
		grid.clearAll();
		grid.load("<c:url value='/app/setup/routes/list'/>",self.load_callback, "json");
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		activeCellContent("<fmt:message key='setup.routes.title'/>",V_NETWORK_ROUTE,function(){
			self.reload();
		});
		
		setRefresh(cellContent, function(){
			self.reload();
		});
	};
	
	this.load_callback=function(){
		cellContent.progressOff();
	};
}

//-------------------- Menu links ----------------
function MenuLinks(){
	var self=this;
	
	this.init=function(){
		cellManageAndView.attachObject("id_menu_ln");
		// 高亮选中的链接
		$(".m-link").click(function(){
		    $(".m-link").css("font-weight","normal");
	        $(this).css("font-weight","bold");
		});
	};
}

//-------------- Conference Reservation View ------------
function ConfReserveView(){
	var CONF_RESERVE_VIEW="v_conf_reserve",self=this,inited=false,reservationObj=null,
	date2StrFormat=scheduler.date.date_to_str("%Y-%m-%d %H:%i"),str2DateFormat=scheduler.date.str_to_date("%Y-%m-%d");
	
	this.init=function(){
		/*
		调试时使用的
		var toolbar=cellContent.view(CONF_RESERVE_VIEW).attachToolbar();
		toolbar.addButton("id_btn_add",0,"ToJSON");
		
		toolbar.attachEvent("onClick",function(id){
			alert(scheduler.toJSON());
		});
		*/
		cellContent.view(CONF_RESERVE_VIEW).attachObject('id_scheduler');
		
		scheduler.config.show_loading=true;
		scheduler.config.drag_move=false;
		scheduler.config.details_on_create = true;
		scheduler.config.details_on_dblclick = true;
		scheduler.config.drag_resize=false;
		scheduler.config.icons_select=["icon_details","icon_delete"];
		scheduler.config.agenda_start = new Date();
		scheduler.config.agenda_end = scheduler.date.add(new Date(), 1, "month");
		scheduler.config.lightbox_recurring="series";
		
		//Customize agenda description
		scheduler.templates.agenda_text = function(start,end,ev){
			return ev['text'] + "(" + (ev['number']||'') + "):" + (ev['topic']||'');
		};
		scheduler.attachEvent("onBeforeLightbox", function (id){
			//alert("onBeforeLightbox||"+id);
			var ev=scheduler.getEvent(id);
			//alert($.toJSON(ev));
			if(!ev.isNew){//update
				reservationObj=self.getReservationFromServer(self.getId(id));
				if(reservationObj==null){
					//scheduler.deleteEvent(id);
					//alert("<fmt:message key='operation.record.not.exist' />");
					return false;
				}
			}else{
			    // 新建预定会议时，默认弹出周期选择栏
			    ev.rec_pattern="month_1_1_1_";
			    ev.rec_type="month_1_1_1_#no";
			}
			
			return true;
		});
		
		scheduler.attachEvent("onEventCreated", function(id,ev){
			//alert("onEventCreated");
			scheduler.getEvent(id).isNew = true;
			//scheduler.updateEvent(id);
		});
		
		scheduler.attachEvent("onLightbox", function (id){
			self.bindCalToEndTimeInput();
			self.bindNumValidToInput();
			
			// Reset lightbox position
			var $t=$(".dhx_cal_light");
			$t.css({
				left:"50%",
				top:"0",
				marginLeft:	'-' + ($t.outerWidth() / 2) + 'px'
			});
		});
		scheduler.attachEvent("onAfterLightbox", function (){
			reservationObj=null;
		});
		scheduler.attachEvent("onDblClick", function (event_id, native_event_object){
			//alert(event_id);
			scheduler.showLightbox(event_id);
			return false;
		});
		scheduler.attachEvent("onEventSave",function(id,data,is_new_event){
			return self.validate(data);
		});
		scheduler.attachEvent("onBeforeEventDelete", function(id,ev){
			//alert("onBeforeEventDelete||"+id);
			
			if(ev.isNew) return true;
			if(self.removeReservation(self.getId(id))) self.loadEvents();
			//Use server delete action.Do not execute scheduler delete action
			return false;
		});
		scheduler.attachEvent("onEventAdded", function(id,ev){
			//alert("onEventAdded||"+id);
			//alert($.toJSON(scheduler.getEvent(id)));
			if(ev.isNew){
				scheduler.getEvent(id).isNew = false;
				//scheduler.updateEvent(id);
				var params=$.parseJSON(self.getConfInfoFromIframe(document.getElementById("conf_iframe")));
				
				params["id"]=self.getId(ev["id"]);
				params["start_date"]=date2StrFormat(ev["start_date"]);
				params["end_date"]=date2StrFormat(ev["end_date"]);
				params["rec_type"]=ev["rec_type"]||"";
				params["event_length"]=ev["event_length"]||"";
				params["times"]=new Date().valueOf();
				params["participantsJSON"]=params["participants"]?$.toJSON(params["participants"]):"[]";
				delete params['participants'];
				//alert($.toJSON(params));
				self.addReservation(params);
			}
		});
		scheduler.attachEvent("onEventChanged", function(id,ev){
			//alert("onEventChanged");
			var params=$.parseJSON(self.getConfInfoFromIframe(document.getElementById("conf_iframe")));
			
			params["id"]=self.getId(ev["id"]);
			params["start_date"]=date2StrFormat(ev["start_date"]);
			params["end_date"]=date2StrFormat(ev["end_date"]);
			params["rec_type"]=ev["rec_type"]||"";
			params["event_length"]=ev["event_length"]||"";
			params["times"]=new Date().valueOf();
			params["participantsJSON"]=params["participants"]?$.toJSON(params["participants"]):"[]";
			delete params['participants'];
			
			//alert($.toJSON(ev));
			self.updateReservation(params);
		});
		
		self.buildLightbox();
		
		scheduler.config.xml_date="%Y-%m-%d %H:%i";
		scheduler.config.repeat_date="%Y-%m-%d";
		
		scheduler.init('id_scheduler',null,'week');
		
		inited=true;
	};
	
	this.getId=function(id){
		if(id.toString().indexOf("#")!=-1) 
			return id.toString().split("#")[0];
		else 
			return id;
	};
	
	this.getReservationFromServer=function(id){
		if(!id) return null;
		
		var ret=null;
		
		$.ajax({
			url:"<c:url value='/app/manage/conf/reserve/json' />",
			type:"GET",
			async:false,
			data:{
				times:new Date().toString(),
				id:id||""
			},
			success:function(jsonStr){
				var jsonObj=$.parseJSON(jsonStr);
				if(jsonObj.success=="true"&&jsonObj.data){
					ret=jsonObj.data;
				}else if(jsonObj.success=="false"){
					alert(jsonObj.data);
				}
			}
		});
		
		return ret;
	};
	
	this.getReservationObj=function(){
		return reservationObj;
	};
	
	this.addReservation=function(params){
		if(!params) return;
		
		$.ajax({
			url:"<c:url value='/app/manage/conf/reserve' />",
			type:"POST",
			//async:false,
			data:params,
			success:function(data){
				if(data!="<fmt:message key='operation.success' />")
					alert(data);
				
				self.loadEvents();
			}
		});
	};
	
	this.updateReservation=function(params){
		if(!params) return;
		
		params["_method"]="PUT";
		$.ajax({
			url:"<c:url value='/app/manage/conf/reserve' />",
			type:"POST",
			//async:false,
			data:params,
			success:function(data){
				if(data!="<fmt:message key='operation.success' />")
					alert(data);
				
				self.loadEvents();
			}
		});
	};
	
	this.removeReservation=function(id){
		var ret=false;
		$.ajax({
			url:"<c:url value='/app/manage/conf/reserve' />",
			type:"POST",
			async:false,
			data:{
				times:new Date().valueOf(),
				id:id,
				"_method":"DELETE"
			},
			success:function(data){
				if(data=="<fmt:message key='operation.success' />"){
					ret=true;
				}else{//show error message when operation fail
					alert(data);
				}
			}
		});
		return ret;
	};
	
	this.active=function(){
		if(!inited) this.init();
		
		activeCellContent("<fmt:message key='conf.reservation.title'/>",CONF_RESERVE_VIEW,function(){
			self.loadEvents();
			scheduler.updateView();
		});
	};
	//Load recurring events from server.
	this.loadEvents=function(){
		$.ajax({
			url:"<c:url value='/app/manage/conf/reserve/list/json'/>",
			type:"GET",
			data:{
				times:new Date().toString()
			},
			success:function(data){
				//alert(data);
				scheduler.clearAll();
				//alert($.parseJSON(data));
				scheduler.parse($.parseJSON(data),"json");
			}
		});
	};
	
	this.resizeScheduler=function(){
		if(inited&&cellContent&&cellContent.av==self.getViewName()){
			scheduler.updateView();
		}
	};
	
	this.getViewName=function(){
		return CONF_RESERVE_VIEW;
	};
	
	this.getSchedulerValues=function(){
		return scheduler.toJSON();
	};
	
	this.getConfInfoFromIframe=function(ifrm){
		return ifrm.contentWindow.confInfoObj.getConfValues();
	};
	
	this.getText=function(ifrm){
		return ifrm.contentWindow.confInfoObj.getText();
	};
	
	this.getConfNumber=function(ifrm){
		return ifrm.contentWindow.confInfoObj.getConfNumber();
	};
	
	this.getConfTopic=function(ifrm){
		return ifrm.contentWindow.confInfoObj.getConfTopic();
	};
	
	/**
	 * Customize lightbox sections
	 */
	this.buildLightbox=function(){
		scheduler.form_blocks["conf_editor"]={
			render:function(sns){
				return '<iframe height="330" width="100%" frameBorder="0" id="conf_iframe"></iframe>';
			},
			set_value:function(node,text,ev){
				node.src='<c:url value="/app/manage/conf/reserve/enter" />?times='+new Date().valueOf();
			},
			get_value:function(node,ev){
				ev["number"]=self.getConfNumber(node);
				ev["topic"]=self.getConfTopic(node);
				
				//alert(ev["number"]+"||"+ev["topic"]);
				return self.getText(node);
			},
			focus:function(node){
				//Nothing now
			}
		};

		scheduler.config.lightbox.sections=[	 
		                                	{name:"description", height:130, map_to:"text", type:"conf_editor"},
		                                	{name:"recurring", height:80, type:"recurring", map_to:"rec_type", button:"recurring"},
		                                	{name:"time", height:72, type:"time", map_to:"auto"}
		                                	];
	};
	/**
	 * Validate lightbox values including conference information
	 */
	this.validate=function(data){
		var $s=$(".dhx_section_time").find("select");
		var sDate=new Date($s[3].value,$s[2].value,$s[1].value,0,$s[0].value);
		var eDate=new Date($s[7].value,$s[6].value,$s[5].value,0,$s[4].value);
		var $repeatDiv=$(".dhx_form_repeat");
		var $repeatRightDiv=$(".dhx_repeat_right");
		
		if($repeatDiv.height()){// repead is enabled
			if($repeatRightDiv.find("input:radio")[2].checked){// if terminate by end time
				var recEndDate=$repeatRightDiv.find(".dhx_repeat_date").val();
				if(!xdate.isDate(recEndDate)){
					alert("<fmt:message key='common.tip.invalid.date' />");
					return false;
				}else{
					eDate=str2DateFormat(recEndDate);
				}
			}
		}
		
		// Validate time period
		if(sDate>=eDate){
			alert("<fmt:message key='common.tip.illegal.period' />");
			return false;
		}
		
		// Validate conference information
		if(!self.validConf()){
			alert("<fmt:message key='common.tip.illegal.conf' />");
			return false;
		}
		
		return true;
	};
	
	this.validConf=function(){
		return document.getElementById("conf_iframe").contentWindow.confInfoObj.isValidValues();
	};
	
	/**
	 * Bind calendar to end time input and set the input readonly
	 */
	this.bindCalToEndTimeInput=function(){
		$(".dhx_repeat_right").find("input.dhx_repeat_date").attr("id","__repeat_date__").attr("readonly",true).val(function(){
			var today=new Date();
			var format=scheduler.date.date_to_str("%Y-%m-%d");
			return this.value==""?format(new Date(today.getFullYear(),today.getMonth()+1,today.getDate())):this.value;
		});
		
		var myCalendar = new dhtmlXCalendarObject(["__repeat_date__"]);
        myCalendar.hideTime();
	};
	/**
	 * Bind number validation to input elements in recurring section
	 */
	this.bindNumValidToInput=function(){
		$(".dhx_form_repeat").find(".dhx_repeat_text").blur(function(){
			var v=this.value;
			if(!/^[1-9]\d*$/.test(v)){
				this.value=1;
			}
		});
	};
}

function MCUDatetime(){
	var self=this;
	
	this.init=function(){
		self.setMCUDatetime();
	};
	
	this.start=function(){
		//interval is 30 seconds
		setInterval(function(){
			self.setMCUDatetime();
		},31*1000);
	};
	
	this.setMCUDatetime=function(){
		var datetime=self.getMCUDatetime();
		$("#lab_mcu_datetime").html(datetime);
	};
	
	this.getMCUDatetime=function(){
		var datetime="";
		
		$.ajax({
			url:"<c:url value='/app/view/mcuDatetime'/>",
			type:"GET",
			async:false,
			data:{
				times:new Date().valueOf()
			},
			success:function(data){
				var jsonRet=$.parseJSON(data);
                // If jsonRet.datetime is defined, used. Otherwise use ""
				datetime=jsonRet.datetime||"";
			}
		});
		
		return datetime;
	};
}
